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

265 lines
9.7 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
  8. import emoji
  9. import pygame
  10. import pytchat
  11. from playsound import playsound
  12. from pygame.locals import *
  13. from aques import Aques
  14. from common_const import *
  15. from common_module import CommonModule
  16. from mode import Mode
  17. from othello import Othello
  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. othello = Othello (screen)
  43. # 吹き出し
  44. balloon = pygame.transform.scale (pygame.image.load ('talking.png'),
  45. (CWindow.WIDTH, 384))
  46. if goatoh_mode:
  47. balloon = pygame.transform.flip (balloon, False, True)
  48. # 背景(夕方)
  49. bg_evening: pygame.Surface = pygame.transform.scale (
  50. pygame.image.load ('bg-evening.jpg'),
  51. (CWindow.WIDTH, CWindow.HEIGHT))
  52. # 背景(夜)
  53. bg_night: pygame.Surface = pygame.transform.scale (
  54. pygame.image.load ('bg-night.jpg'),
  55. (CWindow.WIDTH, CWindow.HEIGHT))
  56. # 音声再生器の初期化
  57. pygame.mixer.init (frequency = 44100)
  58. # ニジカの “ぬ゛ぅ゛ぅ゛ぅ゛ん゛”
  59. noon = pygame.mixer.Sound ('noon.wav')
  60. # ゴートうの “ムムムム”
  61. mumumumu = pygame.mixer.Sound ('mumumumu.wav')
  62. # ゴートうの “クサタベテル!!”
  63. kusa = pygame.mixer.Sound ('kusa.wav')
  64. # YouTube Chat オブジェクト
  65. live_chat = pytchat.create (video_id = YOUTUBE_ID)
  66. # デバッグ・メシジのフォント
  67. system_font = pygame.font.SysFont ('notosanscjkjp', 24, bold = True)
  68. # 視聴者コメントのフォント
  69. user_font = pygame.font.SysFont ('notosanscjkjp', 32, italic = True)
  70. # ニジカのフォント
  71. nizika_font = pygame.font.SysFont ('07nikumarufont', 50)
  72. # Youtube Chat から取得したコメントたち
  73. chat_items: list = []
  74. # 会話の履歴(3 件分保持)
  75. histories: list = []
  76. while (True):
  77. cls.draw_bg (screen, bg_evening, bg_night)
  78. # 左上に時刻表示
  79. for i in range (4):
  80. screen.blit (
  81. system_font.render (str (datetime.now ()), True, (0, 0, 0)),
  82. (i % 2, i // 2 * 2))
  83. if live_chat.is_alive ():
  84. # Chat オブジェクトが有効
  85. # Chat 取得
  86. chat_items: list = live_chat.get ().items
  87. if chat_items:
  88. # 溜まってゐる Chat からランダムに 1 つ抽出
  89. chat_item = random.choice (chat_items)
  90. # 投稿者情報を辞書化
  91. chat_item.author = chat_item.author.__dict__
  92. # 絵文字を復元
  93. chat_item.message = emoji.emojize (chat_item.message)
  94. message: str = chat_item.message
  95. if nizika_mode:
  96. goatoh_talking = False
  97. if goatoh_mode:
  98. goatoh_talking = True
  99. if double_mode:
  100. goatoh_talking: bool = random.random () < .5
  101. while True:
  102. # ChatGPT API を呼出し,返答を取得
  103. answer: str = Talk.main (message, chat_item.author['name'], histories, goatoh_talking).replace ('\n', ' ')
  104. # 履歴に追加
  105. histories = (histories
  106. + [{'role': 'user', 'content': message},
  107. {'role': 'assistant', 'content': answer}])[(-12):]
  108. # ログ書込み
  109. with open ('log.txt', 'a') as f:
  110. f.write (f'{datetime.now ()}\t{json.dumps (chat_item.__dict__)}\t{answer}\n')
  111. # 吹出し描画(ニジカは上,ゴートうは下)
  112. if nizika_mode:
  113. screen.blit (balloon, (0, 0))
  114. if goatoh_mode:
  115. screen.blit (balloon, (0, 384))
  116. if double_mode:
  117. screen.blit (pygame.transform.flip (
  118. balloon,
  119. not goatoh_talking,
  120. False),
  121. (0, 0))
  122. # 視聴者コメント描画
  123. screen.blit (
  124. user_font.render (
  125. '> ' + (message
  126. if (CommonModule.len_by_full (message)
  127. <= 21)
  128. else (CommonModule.mid_by_full (
  129. message, 0, 19.5)
  130. + '...')),
  131. True,
  132. (0, 0, 0)),
  133. (120, 70 + 384) if goatoh_mode else (120 + (64 if (double_mode and not goatoh_talking) else 0), 70))
  134. # ニジカの返答描画
  135. screen.blit (
  136. nizika_font.render (
  137. (answer
  138. if CommonModule.len_by_full (answer) <= 16
  139. else CommonModule.mid_by_full (answer, 0, 16)),
  140. True,
  141. (192, 0, 0)),
  142. (100, 150 + 384) if goatoh_mode else (100 + (64 if (double_mode and not goatoh_talking) else 0), 150))
  143. if CommonModule.len_by_full (answer) > 16:
  144. screen.blit (
  145. nizika_font.render (
  146. (CommonModule.mid_by_full (answer, 16, 16)
  147. if CommonModule.len_by_full (answer) <= 32
  148. else (CommonModule.mid_by_full (
  149. answer, 16, 14.5)
  150. + '...')),
  151. True,
  152. (192, 0, 0)),
  153. (100, 200 + 384) if goatoh_mode else (100 + (64 if (double_mode and not goatoh_talking) else 0), 200))
  154. pygame.display.update ()
  155. # 鳴く.
  156. if goatoh_talking:
  157. if random.random () < .1:
  158. kusa.play ()
  159. else:
  160. mumumumu.play ()
  161. else:
  162. noon.play ()
  163. time.sleep (1.5)
  164. # 返答の読上げを WAV ディタとして生成,取得
  165. try:
  166. wav: bytearray | None = Aques.main (answer, goatoh_talking)
  167. except:
  168. wav: None = None
  169. # 読上げを再生
  170. if wav is not None:
  171. with open ('./nizika_talking.wav', 'wb') as f:
  172. f.write (wav)
  173. playsound ('./nizika_talking.wav')
  174. time.sleep (1)
  175. if not double_mode or random.random () < .5:
  176. break
  177. cls.draw_bg (screen, bg_evening, bg_night)
  178. chat_item.author = {'name': 'ゴートうひとり' if goatoh_talking else '伊地知ニジカ',
  179. 'id': '',
  180. 'imageUrl': './favicon-goatoh.ico' if goatoh_talking else './favicon.ico'}
  181. chat_item.message = histories.pop (-1)['content']
  182. message = chat_item.message
  183. goatoh_talking = not goatoh_talking
  184. else:
  185. # Chat オブジェクトが無効
  186. # 再生成
  187. live_chat = pytchat.create (video_id = YOUTUBE_ID)
  188. pygame.display.update ()
  189. for event in pygame.event.get ():
  190. if event.type == QUIT:
  191. pygame.quit ()
  192. sys.exit ()
  193. @classmethod
  194. def draw_bg (
  195. cls,
  196. screen: pygame.Surface,
  197. bg_evening: pygame.Surface,
  198. bg_night: pygame.Surface) \
  199. -> None:
  200. if 17 <= (h := datetime.now ().hour) < 18:
  201. screen.blit (bg_evening, (0, 0))
  202. elif (h < 6) or (18 <= h):
  203. screen.blit (bg_night, (0, 0))
  204. else:
  205. screen.fill ((0, 255, 0))
  206. if __name__ == '__main__':
  207. Main.main (sys.argv, len (sys.argv))