伊地知ニジカ放送局だぬ゛ん゛. 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 16 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
4 months ago
8 months ago
9 months ago
4 months ago
4 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
4 months ago
4 months ago
4 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 pygame.gfxdraw
  12. import pytchat
  13. from playsound import playsound
  14. from pygame.locals import *
  15. from aques import Aques
  16. from common_const import *
  17. from common_module import CommonModule
  18. from mode import Mode
  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. observer = ephem.Observer ()
  44. observer.lat, observer.lon = '35', '139'
  45. # き太く陽オブジェクト
  46. sun = ephem.Sun ()
  47. # 大月ヨヨコ・オブジェクト
  48. moon = ephem.Moon ()
  49. # 吹き出し
  50. balloon = pygame.transform.scale (pygame.image.load ('talking.png'),
  51. (CWindow.WIDTH, 384))
  52. if goatoh_mode:
  53. balloon = pygame.transform.flip (balloon, False, True)
  54. # 背景(昼)
  55. bg_day: pygame.Surface = pygame.transform.scale (
  56. pygame.image.load ('bg.jpg'),
  57. (CWindow.WIDTH, CWindow.HEIGHT))
  58. # 背景(夕方)
  59. bg_evening: pygame.Surface = pygame.transform.scale (
  60. pygame.image.load ('bg-evening.jpg'),
  61. (CWindow.WIDTH, CWindow.HEIGHT))
  62. # 背景(夜)
  63. bg_night: pygame.Surface = pygame.transform.scale (
  64. pygame.image.load ('bg-night.jpg'),
  65. (CWindow.WIDTH, CWindow.HEIGHT))
  66. # 背景の草
  67. bg_grass: pygame.Surface = pygame.transform.scale (
  68. pygame.image.load ('bg-grass.png'),
  69. (CWindow.WIDTH, CWindow.HEIGHT))
  70. # き太く陽
  71. kita: pygame.Surface = pygame.transform.scale (
  72. pygame.image.load ('sun.png'), (200, 200))
  73. # 大月ヨヨコ
  74. jojoko: pygame.Surface = pygame.transform.scale (
  75. pygame.image.load ('moon.png'), (200, 200))
  76. # 音声再生器の初期化
  77. pygame.mixer.init (frequency = 44100)
  78. # ニジカの “ぬ゛ぅ゛ぅ゛ぅ゛ん゛”
  79. noon = pygame.mixer.Sound ('noon.wav')
  80. # ゴートうの “ムムムム”
  81. mumumumu = pygame.mixer.Sound ('mumumumu.wav')
  82. # ゴートうの “クサタベテル!!”
  83. kusa = pygame.mixer.Sound ('kusa.wav')
  84. # YouTube Chat オブジェクト
  85. live_chat = pytchat.create (video_id = YOUTUBE_ID)
  86. # デバッグ・メシジのフォント
  87. system_font = pygame.font.SysFont ('notosanscjkjp', 24, bold = True)
  88. # 視聴者コメントのフォント
  89. user_font = pygame.font.SysFont ('notosanscjkjp', 32, italic = True)
  90. # ニジカのフォント
  91. nizika_font = pygame.font.SysFont ('07nikumarufont', 50)
  92. # Youtube Chat から取得したコメントたち
  93. chat_items: list = []
  94. # 会話の履歴
  95. histories: list = []
  96. while (True):
  97. # 観測地の日づけ更新
  98. observer.date: datetime = datetime.now ().date ()
  99. # 日の出開始
  100. sunrise_start: datetime = (
  101. (ephem.localtime (observer.previous_rising (sun))
  102. - timedelta (minutes = 30)))
  103. # 日の出終了
  104. sunrise_end: datetime = sunrise_start + timedelta (hours = 1)
  105. # 日の入開始
  106. sunset_start: datetime = (
  107. (ephem.localtime (observer.next_setting (sun))
  108. - timedelta (minutes = 30)))
  109. # 日の入終了
  110. sunset_end: datetime = sunset_start + timedelta (hours = 1)
  111. # 時刻つき観測地
  112. observer_with_time: ephem.Observer = observer
  113. observer_with_time.date = datetime.now () - timedelta (hours = 9)
  114. # 日の角度
  115. sun.compute (observer_with_time)
  116. sun_alt: float = CommonModule.rad_to_deg (sun.alt)
  117. # 月の角度
  118. moon.compute (observer_with_time)
  119. moon_alt: float = CommonModule.rad_to_deg (moon.alt)
  120. # 月齢
  121. new_moon_dt: datetime = ephem.localtime (
  122. ephem.previous_new_moon (observer_with_time.date))
  123. moon_days_old: float = (
  124. (datetime.now () - new_moon_dt).total_seconds ()
  125. / 60 / 60 / 24)
  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, moon_alt, moon_days_old)
  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, moon_alt, moon_days_old)
  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_original: pygame.Surface,
  263. sunrise_start: datetime,
  264. sunrise_end: datetime,
  265. sunset_start: datetime,
  266. sunset_end: datetime,
  267. sun_alt: float,
  268. moon_alt: float,
  269. moon_days_old: float) \
  270. -> None:
  271. sunrise_centre: datetime = (
  272. sunrise_start + (sunrise_end - sunrise_start) / 2)
  273. sunset_centre: datetime = (
  274. sunset_start + (sunset_end - sunset_start) / 2)
  275. jojoko: pygame.Surface = cls.get_jojoko (jojoko_original,
  276. moon_days_old)
  277. dt: datetime = datetime.now ()
  278. if sunrise_centre <= dt < sunset_centre:
  279. screen.blit (bg_day, (0, 0))
  280. else:
  281. screen.blit (bg_night, (0, 0))
  282. if sunrise_start <= dt < sunrise_end:
  283. bg_evening.set_alpha (255 - ((abs (dt - sunrise_centre) * 510)
  284. / (sunrise_end - sunrise_centre)))
  285. elif sunset_start <= dt < sunset_end:
  286. bg_evening.set_alpha (255 - ((abs (dt - sunset_centre) * 510)
  287. / (sunset_end - sunset_centre)))
  288. else:
  289. bg_evening.set_alpha (0)
  290. if sunrise_start <= dt < sunset_end:
  291. jojoko.set_alpha (255 - 255 / 15 * abs (moon_days_old - 15))
  292. else:
  293. jojoko.set_alpha (255)
  294. screen.blit (bg_evening, (0, 0))
  295. if -10 <= moon_alt < 40:
  296. y = ((CWindow.HEIGHT / 2 + 100)
  297. - (CWindow.HEIGHT / 2 + 200) / 30 * moon_alt)
  298. screen.blit (jojoko, jojoko.get_rect (center = (400, y)))
  299. screen.blit (bg_grass, (0, 0))
  300. if -10 <= sun_alt < 40:
  301. y = ((CWindow.HEIGHT / 2 + 100)
  302. - (CWindow.HEIGHT / 2 + 200) / 30 * sun_alt)
  303. screen.blit (kita, kita.get_rect (center = (400, y)))
  304. screen.blit (bg_grass, (0, 0))
  305. @classmethod
  306. def get_jojoko (
  307. cls,
  308. jojoko_original: pygame.Surface,
  309. moon_days_old: float) \
  310. -> pygame.Surface:
  311. jojoko: pygame.Surface = jojoko_original.copy ()
  312. jojoko.set_colorkey ((0, 255, 0))
  313. for i in range (200):
  314. if 1 <= moon_days_old < 7:
  315. pygame.gfxdraw.bezier (jojoko, ((0, 100 + i), (100, 180 * moon_days_old / 7 - 80 + i), (200, 100 + i)), 3, (0, 255, 0))
  316. elif moon_days_old < 14:
  317. pygame.gfxdraw.bezier (jojoko, ((0, 100 + i), (100, 180 * moon_days_old / 7 - 80 + i), (200, 100 + i)), 3, (0, 255, 0))
  318. elif moon_days_old < 15:
  319. pass
  320. elif moon_days_old < 22:
  321. pygame.gfxdraw.bezier (jojoko, ((0, 100 - i), (100, 180 * (moon_days_old - 15) / 7 - 80 - i), (200, 100 - i)), 3, (0, 255, 0))
  322. elif moon_days_old < 30:
  323. pygame.gfxdraw.bezier (jojoko, ((0, 100 - i), (100, 180 * (moon_days_old - 15) / 7 - 80 - i), (200, 100 - i)), 3, (0, 255, 0))
  324. else:
  325. jojoko.fill ((0, 255, 0))
  326. return jojoko
  327. if __name__ == '__main__':
  328. Main.main (sys.argv, len (sys.argv))