伊地知ニジカ放送局だぬ゛ん゛. 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 18 KiB

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