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

332 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. 'todo'
  104. # 月の出終了
  105. 'todo'
  106. # 月の入開始
  107. 'todo'
  108. # 月の入終了
  109. 'todo'
  110. # 左上に時刻表示
  111. for i in range (4):
  112. screen.blit (
  113. system_font.render (str (datetime.now ()), True, (0, 0, 0)),
  114. (i % 2, i // 2 * 2))
  115. if live_chat.is_alive ():
  116. # Chat オブジェクトが有効
  117. # Chat 取得
  118. chat_items: list = live_chat.get ().items
  119. if chat_items:
  120. # 溜まってゐる Chat からランダムに 1 つ抽出
  121. chat_item = random.choice (chat_items)
  122. # 投稿者情報を辞書化
  123. chat_item.author = chat_item.author.__dict__
  124. # 絵文字を復元
  125. chat_item.message = emoji.emojize (chat_item.message)
  126. message: str = chat_item.message
  127. if nizika_mode:
  128. goatoh_talking = False
  129. if goatoh_mode:
  130. goatoh_talking = True
  131. if double_mode:
  132. goatoh_talking: bool = random.random () < .5
  133. while True:
  134. # ChatGPT API を呼出し,返答を取得
  135. answer: str = Talk.main (message, chat_item.author['name'], histories, goatoh_talking).replace ('\n', ' ')
  136. # 履歴に追加
  137. histories = (histories
  138. + [{'role': 'user', 'content': message},
  139. {'role': 'assistant', 'content': answer}])[(-12):]
  140. # ログ書込み
  141. with open ('log.txt', 'a') as f:
  142. f.write (f'{datetime.now ()}\t{json.dumps (chat_item.__dict__)}\t{answer}\n')
  143. # 吹出し描画(ニジカは上,ゴートうは下)
  144. if nizika_mode:
  145. screen.blit (balloon, (0, 0))
  146. if goatoh_mode:
  147. screen.blit (balloon, (0, 384))
  148. if double_mode:
  149. screen.blit (pygame.transform.flip (
  150. balloon,
  151. not goatoh_talking,
  152. False),
  153. (0, 0))
  154. # 視聴者コメント描画
  155. screen.blit (
  156. user_font.render (
  157. '> ' + (message
  158. if (CommonModule.len_by_full (message)
  159. <= 21)
  160. else (CommonModule.mid_by_full (
  161. message, 0, 19.5)
  162. + '...')),
  163. True,
  164. (0, 0, 0)),
  165. (120, 70 + 384) if goatoh_mode else (120 + (64 if (double_mode and not goatoh_talking) else 0), 70))
  166. # ニジカの返答描画
  167. screen.blit (
  168. nizika_font.render (
  169. (answer
  170. if CommonModule.len_by_full (answer) <= 16
  171. else CommonModule.mid_by_full (answer, 0, 16)),
  172. True,
  173. (192, 0, 0)),
  174. (100, 150 + 384) if goatoh_mode else (100 + (64 if (double_mode and not goatoh_talking) else 0), 150))
  175. if CommonModule.len_by_full (answer) > 16:
  176. screen.blit (
  177. nizika_font.render (
  178. (CommonModule.mid_by_full (answer, 16, 16)
  179. if CommonModule.len_by_full (answer) <= 32
  180. else (CommonModule.mid_by_full (
  181. answer, 16, 14.5)
  182. + '...')),
  183. True,
  184. (192, 0, 0)),
  185. (100, 200 + 384) if goatoh_mode else (100 + (64 if (double_mode and not goatoh_talking) else 0), 200))
  186. pygame.display.update ()
  187. # 鳴く.
  188. if goatoh_talking:
  189. if random.random () < .1:
  190. kusa.play ()
  191. else:
  192. mumumumu.play ()
  193. else:
  194. noon.play ()
  195. time.sleep (1.5)
  196. # 返答の読上げを WAV ディタとして生成,取得
  197. try:
  198. wav: bytearray | None = Aques.main (answer, goatoh_talking)
  199. except:
  200. wav: None = None
  201. # 読上げを再生
  202. if wav is not None:
  203. with open ('./nizika_talking.wav', 'wb') as f:
  204. f.write (wav)
  205. playsound ('./nizika_talking.wav')
  206. time.sleep (1)
  207. if not double_mode or random.random () < .5:
  208. break
  209. cls.draw_bg (screen, bg_day, bg_evening, bg_night,
  210. sunrise_start, sunrise_end,
  211. sunset_start, sunset_end)
  212. chat_item.author = {'name': 'ゴートうひとり' if goatoh_talking else '伊地知ニジカ',
  213. 'id': '',
  214. 'imageUrl': './favicon-goatoh.ico' if goatoh_talking else './favicon.ico'}
  215. chat_item.message = histories.pop (-1)['content']
  216. message = chat_item.message
  217. goatoh_talking = not goatoh_talking
  218. else:
  219. # Chat オブジェクトが無効
  220. # 再生成
  221. live_chat = pytchat.create (video_id = YOUTUBE_ID)
  222. pygame.display.update ()
  223. for event in pygame.event.get ():
  224. if event.type == QUIT:
  225. pygame.quit ()
  226. sys.exit ()
  227. @classmethod
  228. def draw_bg (
  229. cls,
  230. screen: pygame.Surface,
  231. bg_day: pygame.Surface,
  232. bg_evening: pygame.Surface,
  233. bg_night: pygame.Surface,
  234. sunrise_start: datetime,
  235. sunrise_end: datetime,
  236. sunset_start: datetime,
  237. sunset_end: datetime) \
  238. -> None:
  239. sunrise_centre: datetime = (
  240. sunrise_start + (sunrise_end - sunrise_start) / 2)
  241. sunset_centre: datetime = (
  242. sunset_start + (sunset_end - sunset_start) / 2)
  243. dt: datetime = datetime.now ()
  244. if sunrise_centre <= dt < sunset_centre:
  245. screen.blit (bg_day, (0, 0))
  246. else:
  247. screen.blit (bg_night, (0, 0))
  248. if sunrise_start <= dt < sunrise_end:
  249. bg_evening.set_alpha (255 - ((abs (dt - sunrise_centre) * 510)
  250. / (sunrise_end - sunrise_centre)))
  251. elif sunset_start <= dt < sunset_end:
  252. bg_evening.set_alpha (255 - ((abs (dt - sunset_centre) * 510)
  253. / (sunset_end - sunset_centre)))
  254. else:
  255. return
  256. screen.blit (bg_evening, (0, 0))
  257. if __name__ == '__main__':
  258. Main.main (sys.argv, len (sys.argv))