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

320 lines
12 KiB

  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. pygame.mixer.init (frequency = 44100)
  67. # ニジカの “ぬ゛ぅ゛ぅ゛ぅ゛ん゛”
  68. noon = pygame.mixer.Sound ('noon.wav')
  69. # ゴートうの “ムムムム”
  70. mumumumu = pygame.mixer.Sound ('mumumumu.wav')
  71. # ゴートうの “クサタベテル!!”
  72. kusa = pygame.mixer.Sound ('kusa.wav')
  73. # YouTube Chat オブジェクト
  74. live_chat = pytchat.create (video_id = YOUTUBE_ID)
  75. # デバッグ・メシジのフォント
  76. system_font = pygame.font.SysFont ('notosanscjkjp', 24, bold = True)
  77. # 視聴者コメントのフォント
  78. user_font = pygame.font.SysFont ('notosanscjkjp', 32, italic = True)
  79. # ニジカのフォント
  80. nizika_font = pygame.font.SysFont ('07nikumarufont', 50)
  81. # Youtube Chat から取得したコメントたち
  82. chat_items: list = []
  83. # 会話の履歴(3 件分保持)
  84. histories: list = []
  85. while (True):
  86. # 観測値の日づけ更新
  87. observer.date: datetime = datetime.now ().date ()
  88. # 日の出開始
  89. sunrise_start: datetime = (
  90. (ephem.localtime (observer.previous_rising (sun))
  91. - timedelta (minutes = 30)))
  92. # 日の出終了
  93. sunrise_end: datetime = sunrise_start + timedelta (hours = 1)
  94. # 日の入開始
  95. sunset_start: datetime = (
  96. (ephem.localtime (observer.next_setting (sun))
  97. - timedelta (minutes = 30)))
  98. # 日の入終了
  99. sunset_end: datetime = sunset_start + timedelta (hours = 1)
  100. cls.draw_bg (screen, bg_day, bg_evening, bg_night,
  101. sunrise_start, sunrise_end, sunset_start, sunset_end)
  102. # 左上に時刻表示
  103. for i in range (4):
  104. screen.blit (
  105. system_font.render (str (datetime.now ()), True, (0, 0, 0)),
  106. (i % 2, i // 2 * 2))
  107. if live_chat.is_alive ():
  108. # Chat オブジェクトが有効
  109. # Chat 取得
  110. chat_items: list = live_chat.get ().items
  111. if chat_items:
  112. # 溜まってゐる Chat からランダムに 1 つ抽出
  113. chat_item = random.choice (chat_items)
  114. # 投稿者情報を辞書化
  115. chat_item.author = chat_item.author.__dict__
  116. # 絵文字を復元
  117. chat_item.message = emoji.emojize (chat_item.message)
  118. message: str = chat_item.message
  119. if nizika_mode:
  120. goatoh_talking = False
  121. if goatoh_mode:
  122. goatoh_talking = True
  123. if double_mode:
  124. goatoh_talking: bool = random.random () < .5
  125. while True:
  126. # ChatGPT API を呼出し,返答を取得
  127. answer: str = Talk.main (message, chat_item.author['name'], histories, goatoh_talking).replace ('\n', ' ')
  128. # 履歴に追加
  129. histories = (histories
  130. + [{'role': 'user', 'content': message},
  131. {'role': 'assistant', 'content': answer}])[(-12):]
  132. # ログ書込み
  133. with open ('log.txt', 'a') as f:
  134. f.write (f'{datetime.now ()}\t{json.dumps (chat_item.__dict__)}\t{answer}\n')
  135. # 吹出し描画(ニジカは上,ゴートうは下)
  136. if nizika_mode:
  137. screen.blit (balloon, (0, 0))
  138. if goatoh_mode:
  139. screen.blit (balloon, (0, 384))
  140. if double_mode:
  141. screen.blit (pygame.transform.flip (
  142. balloon,
  143. not goatoh_talking,
  144. False),
  145. (0, 0))
  146. # 視聴者コメント描画
  147. screen.blit (
  148. user_font.render (
  149. '> ' + (message
  150. if (CommonModule.len_by_full (message)
  151. <= 21)
  152. else (CommonModule.mid_by_full (
  153. message, 0, 19.5)
  154. + '...')),
  155. True,
  156. (0, 0, 0)),
  157. (120, 70 + 384) if goatoh_mode else (120 + (64 if (double_mode and not goatoh_talking) else 0), 70))
  158. # ニジカの返答描画
  159. screen.blit (
  160. nizika_font.render (
  161. (answer
  162. if CommonModule.len_by_full (answer) <= 16
  163. else CommonModule.mid_by_full (answer, 0, 16)),
  164. True,
  165. (192, 0, 0)),
  166. (100, 150 + 384) if goatoh_mode else (100 + (64 if (double_mode and not goatoh_talking) else 0), 150))
  167. if CommonModule.len_by_full (answer) > 16:
  168. screen.blit (
  169. nizika_font.render (
  170. (CommonModule.mid_by_full (answer, 16, 16)
  171. if CommonModule.len_by_full (answer) <= 32
  172. else (CommonModule.mid_by_full (
  173. answer, 16, 14.5)
  174. + '...')),
  175. True,
  176. (192, 0, 0)),
  177. (100, 200 + 384) if goatoh_mode else (100 + (64 if (double_mode and not goatoh_talking) else 0), 200))
  178. pygame.display.update ()
  179. # 鳴く.
  180. if goatoh_talking:
  181. if random.random () < .1:
  182. kusa.play ()
  183. else:
  184. mumumumu.play ()
  185. else:
  186. noon.play ()
  187. time.sleep (1.5)
  188. # 返答の読上げを WAV ディタとして生成,取得
  189. try:
  190. wav: bytearray | None = Aques.main (answer, goatoh_talking)
  191. except:
  192. wav: None = None
  193. # 読上げを再生
  194. if wav is not None:
  195. with open ('./nizika_talking.wav', 'wb') as f:
  196. f.write (wav)
  197. playsound ('./nizika_talking.wav')
  198. time.sleep (1)
  199. if not double_mode or random.random () < .5:
  200. break
  201. cls.draw_bg (screen, bg_day, bg_evening, bg_night,
  202. sunrise_start, sunrise_end,
  203. sunset_start, sunset_end)
  204. chat_item.author = {'name': 'ゴートうひとり' if goatoh_talking else '伊地知ニジカ',
  205. 'id': '',
  206. 'imageUrl': './favicon-goatoh.ico' if goatoh_talking else './favicon.ico'}
  207. chat_item.message = histories.pop (-1)['content']
  208. message = chat_item.message
  209. goatoh_talking = not goatoh_talking
  210. else:
  211. # Chat オブジェクトが無効
  212. # 再生成
  213. live_chat = pytchat.create (video_id = YOUTUBE_ID)
  214. pygame.display.update ()
  215. for event in pygame.event.get ():
  216. if event.type == QUIT:
  217. pygame.quit ()
  218. sys.exit ()
  219. @classmethod
  220. def draw_bg (
  221. cls,
  222. screen: pygame.Surface,
  223. bg_day: pygame.Surface,
  224. bg_evening: pygame.Surface,
  225. bg_night: pygame.Surface,
  226. sunrise_start: datetime,
  227. sunrise_end: datetime,
  228. sunset_start: datetime,
  229. sunset_end: datetime) \
  230. -> None:
  231. sunrise_centre: datetime = (
  232. sunrise_start + (sunrise_end - sunrise_start) / 2)
  233. sunset_centre: datetime = (
  234. sunset_start + (sunset_end - sunset_start) / 2)
  235. dt: datetime = datetime.now ()
  236. if sunrise_centre <= dt < sunset_centre:
  237. screen.blit (bg_day, (0, 0))
  238. else:
  239. screen.blit (bg_night, (0, 0))
  240. if sunrise_start <= dt < sunrise_end:
  241. bg_evening.set_alpha (255 - ((abs (dt - sunrise_centre) * 510)
  242. / (sunrise_end - sunrise_centre)))
  243. elif sunset_start <= dt < sunset_end:
  244. bg_evening.set_alpha (255 - ((abs (dt - sunset_centre) * 510)
  245. / (sunset_end - sunset_centre)))
  246. else:
  247. return
  248. screen.blit (bg_evening, (0, 0))
  249. if __name__ == '__main__':
  250. Main.main (sys.argv, len (sys.argv))