伊地知ニジカ放送局だぬ゛ん゛. https://www.youtube.com/@deerjika
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.py 14 KiB

9 months ago
9 months ago
5 months ago
5 months ago
5 months ago
5 months ago
9 months ago
5 months ago
9 months ago
9 months ago
9 months ago
9 months ago
8 months ago
9 months ago
4 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. # vim: nosmartindent autoindent
  2. import json
  3. import random
  4. import subprocess
  5. import sys
  6. import time
  7. from datetime import datetime, timedelta
  8. import emoji
  9. import ephem
  10. import pygame
  11. import pytchat
  12. from playsound import playsound
  13. from pygame.locals import *
  14. from aques import Aques
  15. from common_const import *
  16. from common_module import CommonModule
  17. from mode import Mode
  18. from othello import Othello
  19. from talk import Talk
  20. from youtube import *
  21. class Main:
  22. @classmethod
  23. def main (
  24. cls,
  25. argv: list,
  26. argc: int) \
  27. -> None:
  28. mode = Mode.NIZIKA
  29. match (argc > 1) and argv[1]:
  30. case '-g':
  31. mode = Mode.GOATOH
  32. case '-w':
  33. mode = Mode.DOUBLE
  34. nizika_mode: bool = mode == Mode.NIZIKA
  35. goatoh_mode: bool = mode == Mode.GOATOH
  36. double_mode: bool = mode == Mode.DOUBLE
  37. print (mode)
  38. # ウィンドゥの初期化
  39. pygame.init ()
  40. screen: pygame.Surface = pygame.display.set_mode (
  41. (CWindow.WIDTH, CWindow.HEIGHT))
  42. # オセロ用オブジェクト
  43. othello = Othello (screen)
  44. # 大月ヨヨコの観測値
  45. observer = ephem.Observer ()
  46. observer.lat, observer.lon = '35', '139'
  47. # き太く陽オブジェクト
  48. sun = ephem.Sun ()
  49. # 大月ヨヨコ・オブジェクト
  50. moon = ephem.Moon ()
  51. # 吹き出し
  52. balloon = pygame.transform.scale (pygame.image.load ('talking.png'),
  53. (CWindow.WIDTH, 384))
  54. if goatoh_mode:
  55. balloon = pygame.transform.flip (balloon, False, True)
  56. # 背景(昼)
  57. bg_day: pygame.Surface = pygame.transform.scale (
  58. pygame.image.load ('bg.jpg'),
  59. (CWindow.WIDTH, CWindow.HEIGHT))
  60. # 背景(夕方)
  61. bg_evening: pygame.Surface = pygame.transform.scale (
  62. pygame.image.load ('bg-evening.jpg'),
  63. (CWindow.WIDTH, CWindow.HEIGHT))
  64. # 背景(夜)
  65. bg_night: pygame.Surface = pygame.transform.scale (
  66. pygame.image.load ('bg-night.jpg'),
  67. (CWindow.WIDTH, CWindow.HEIGHT))
  68. # 背景の草
  69. bg_grass: pygame.Surface = pygame.transform.scale (
  70. pygame.image.load ('bg-grass.png'),
  71. (CWindow.WIDTH, CWindow.HEIGHT))
  72. # き太く陽
  73. kita: pygame.Surface = pygame.transform.scale (
  74. pygame.image.load ('sun.png'), (200, 200))
  75. # 大月ヨヨコ
  76. jojoko: pygame.Surface = pygame.transform.scale (
  77. pygame.image.load ('moon.png'), (200, 200))
  78. # 音声再生器の初期化
  79. pygame.mixer.init (frequency = 44100)
  80. # ニジカの “ぬ゛ぅ゛ぅ゛ぅ゛ん゛”
  81. noon = pygame.mixer.Sound ('noon.wav')
  82. # ゴートうの “ムムムム”
  83. mumumumu = pygame.mixer.Sound ('mumumumu.wav')
  84. # ゴートうの “クサタベテル!!”
  85. kusa = pygame.mixer.Sound ('kusa.wav')
  86. # YouTube Chat オブジェクト
  87. live_chat = pytchat.create (video_id = YOUTUBE_ID)
  88. # デバッグ・メシジのフォント
  89. system_font = pygame.font.SysFont ('notosanscjkjp', 24, bold = True)
  90. # 視聴者コメントのフォント
  91. user_font = pygame.font.SysFont ('notosanscjkjp', 32, italic = True)
  92. # ニジカのフォント
  93. nizika_font = pygame.font.SysFont ('07nikumarufont', 50)
  94. # Youtube Chat から取得したコメントたち
  95. chat_items: list = []
  96. # 会話の履歴(3 件分保持)
  97. histories: list = []
  98. while (True):
  99. # 観測地の日づけ更新
  100. observer.date: datetime = datetime.now ().date ()
  101. # 日の出開始
  102. sunrise_start: datetime = (
  103. (ephem.localtime (observer.previous_rising (sun))
  104. - timedelta (minutes = 30)))
  105. # 日の出終了
  106. sunrise_end: datetime = sunrise_start + timedelta (hours = 1)
  107. # 日の入開始
  108. sunset_start: datetime = (
  109. (ephem.localtime (observer.next_setting (sun))
  110. - timedelta (minutes = 30)))
  111. # 日の入終了
  112. sunset_end: datetime = sunset_start + timedelta (hours = 1)
  113. # 月の出開始
  114. 'todo'
  115. # 月の出終了
  116. 'todo'
  117. # 月の入開始
  118. 'todo'
  119. # 月の入終了
  120. 'todo'
  121. # 日の角度
  122. observer_with_time: ephem.Observer = observer
  123. observer_with_time.date = datetime.now () - timedelta (hours = 9)
  124. sun.compute (observer_with_time)
  125. sun_alt: float = CommonModule.rad_to_deg (sun.alt)
  126. # 背景描画
  127. cls.draw_bg (screen, bg_day, bg_evening, bg_night, bg_grass,
  128. kita, jojoko,
  129. sunrise_start, sunrise_end, sunset_start, sunset_end,
  130. sun_alt)
  131. # 左上に時刻表示
  132. for i in range (4):
  133. screen.blit (
  134. system_font.render (str (datetime.now ()), True, (0, 0, 0)),
  135. (i % 2, i // 2 * 2))
  136. if live_chat.is_alive ():
  137. # Chat オブジェクトが有効
  138. # Chat 取得
  139. chat_items: list = live_chat.get ().items
  140. if chat_items:
  141. # 溜まってゐる Chat からランダムに 1 つ抽出
  142. chat_item = random.choice (chat_items)
  143. # 投稿者情報を辞書化
  144. chat_item.author = chat_item.author.__dict__
  145. # 絵文字を復元
  146. chat_item.message = emoji.emojize (chat_item.message)
  147. message: str = chat_item.message
  148. if nizika_mode:
  149. goatoh_talking = False
  150. if goatoh_mode:
  151. goatoh_talking = True
  152. if double_mode:
  153. goatoh_talking: bool = random.random () < .5
  154. while True:
  155. # ChatGPT API を呼出し,返答を取得
  156. answer: str = Talk.main (message, chat_item.author['name'], histories, goatoh_talking).replace ('\n', ' ')
  157. # 履歴に追加
  158. histories = (histories
  159. + [{'role': 'user', 'content': message},
  160. {'role': 'assistant', 'content': answer}])[(-12):]
  161. # ログ書込み
  162. with open ('log.txt', 'a') as f:
  163. f.write (f'{datetime.now ()}\t'
  164. + f'{json.dumps (chat_item.__dict__)}\t'
  165. + f'{answer}\n')
  166. # 吹出し描画(ニジカは上,ゴートうは下)
  167. if nizika_mode:
  168. screen.blit (balloon, (0, 0))
  169. if goatoh_mode:
  170. screen.blit (balloon, (0, 384))
  171. if double_mode:
  172. screen.blit (pygame.transform.flip (
  173. balloon,
  174. not goatoh_talking,
  175. False),
  176. (0, 0))
  177. # 視聴者コメント描画
  178. screen.blit (
  179. user_font.render (
  180. '> ' + (message
  181. if (CommonModule.len_by_full (
  182. message)
  183. <= 21)
  184. else (CommonModule.mid_by_full (
  185. message, 0, 19.5)
  186. + '...')),
  187. True,
  188. (0, 0, 0)),
  189. (120, 70 + 384) if goatoh_mode else (120 + (64 if (double_mode and not goatoh_talking) else 0), 70))
  190. # ニジカの返答描画
  191. screen.blit (
  192. nizika_font.render (
  193. (answer
  194. if CommonModule.len_by_full (answer) <= 16
  195. else CommonModule.mid_by_full (answer, 0, 16)),
  196. True,
  197. (192, 0, 0)),
  198. (100, 150 + 384) if goatoh_mode else (100 + (64 if (double_mode and not goatoh_talking) else 0), 150))
  199. if CommonModule.len_by_full (answer) > 16:
  200. screen.blit (
  201. nizika_font.render (
  202. (CommonModule.mid_by_full (answer, 16, 16)
  203. if CommonModule.len_by_full (answer) <= 32
  204. else (CommonModule.mid_by_full (
  205. answer, 16, 14.5)
  206. + '...')),
  207. True,
  208. (192, 0, 0)),
  209. (100, 200 + 384) if goatoh_mode else (100 + (64 if (double_mode and not goatoh_talking) else 0), 200))
  210. pygame.display.update ()
  211. # 鳴く.
  212. if goatoh_talking:
  213. if random.random () < .1:
  214. kusa.play ()
  215. else:
  216. mumumumu.play ()
  217. else:
  218. noon.play ()
  219. time.sleep (1.5)
  220. # 返答の読上げを WAV ディタとして生成,取得
  221. try:
  222. wav: bytearray | None = Aques.main (answer, goatoh_talking)
  223. except:
  224. wav: None = None
  225. # 読上げを再生
  226. if wav is not None:
  227. with open ('./nizika_talking.wav', 'wb') as f:
  228. f.write (wav)
  229. playsound ('./nizika_talking.wav')
  230. time.sleep (1)
  231. if not double_mode or random.random () < .5:
  232. break
  233. cls.draw_bg (screen, bg_day, bg_evening, bg_night,
  234. bg_grass, kita, jojoko,
  235. sunrise_start, sunrise_end,
  236. sunset_start, sunset_end,
  237. sun_alt)
  238. chat_item.author = {'name': 'ゴートうひとり' if goatoh_talking else '伊地知ニジカ',
  239. 'id': '',
  240. 'imageUrl': './favicon-goatoh.ico' if goatoh_talking else './favicon.ico'}
  241. chat_item.message = histories.pop (-1)['content']
  242. message = chat_item.message
  243. goatoh_talking = not goatoh_talking
  244. else:
  245. # Chat オブジェクトが無効
  246. # 再生成
  247. live_chat = pytchat.create (video_id = YOUTUBE_ID)
  248. pygame.display.update ()
  249. for event in pygame.event.get ():
  250. if event.type == QUIT:
  251. pygame.quit ()
  252. sys.exit ()
  253. @classmethod
  254. def draw_bg (
  255. cls,
  256. screen: pygame.Surface,
  257. bg_day: pygame.Surface,
  258. bg_evening: pygame.Surface,
  259. bg_night: pygame.Surface,
  260. bg_grass: pygame.Surface,
  261. kita: pygame.Surface,
  262. jojoko: pygame.Surface,
  263. sunrise_start: datetime,
  264. sunrise_end: datetime,
  265. sunset_start: datetime,
  266. sunset_end: datetime,
  267. sun_alt: float) \
  268. -> None:
  269. sunrise_centre: datetime = (
  270. sunrise_start + (sunrise_end - sunrise_start) / 2)
  271. sunset_centre: datetime = (
  272. sunset_start + (sunset_end - sunset_start) / 2)
  273. dt: datetime = datetime.now ()
  274. if sunrise_centre <= dt < sunset_centre:
  275. screen.blit (bg_day, (0, 0))
  276. else:
  277. screen.blit (bg_night, (0, 0))
  278. if sunrise_start <= dt < sunrise_end:
  279. bg_evening.set_alpha (255 - ((abs (dt - sunrise_centre) * 510)
  280. / (sunrise_end - sunrise_centre)))
  281. elif sunset_start <= dt < sunset_end:
  282. bg_evening.set_alpha (255 - ((abs (dt - sunset_centre) * 510)
  283. / (sunset_end - sunset_centre)))
  284. else:
  285. bg_evening.set_alpha (0)
  286. screen.blit (bg_evening, (0, 0))
  287. if -10 <= sun_alt < 40:
  288. y = ((CWindow.HEIGHT / 2 + 100)
  289. - (CWindow.HEIGHT / 2 + 200) / 30 * sun_alt)
  290. screen.blit (kita, kita.get_rect (center = (400, y)))
  291. screen.blit (bg_grass, (0, 0))
  292. if __name__ == '__main__':
  293. Main.main (sys.argv, len (sys.argv))