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