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