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

986 lines
28 KiB

  1. from __future__ import annotations
  2. import math
  3. import os
  4. import random
  5. import sys
  6. import wave
  7. from datetime import datetime, timedelta
  8. from enum import Enum, auto
  9. from io import BytesIO
  10. from typing import Callable, TypedDict
  11. import cv2
  12. import emoji
  13. import ephem
  14. import numpy as np
  15. import pygame
  16. import pygame.gfxdraw
  17. import pytchat
  18. import requests
  19. from cv2 import VideoCapture
  20. from ephem import Moon, Observer, Sun
  21. from pygame import Rect, Surface
  22. from pygame.font import Font
  23. from pygame.mixer import Sound
  24. from pygame.time import Clock
  25. from pytchat.core.pytchat import PytchatCore
  26. from pytchat.processors.default.processor import Chat
  27. from aques import Aques
  28. from common_module import CommonModule
  29. from nizika_ai.config import DB
  30. from nizika_ai.consts import Character, GPTModel, Platform, QueryType
  31. from nizika_ai.models import Answer, AnsweredFlag, Query, User
  32. pygame.init ()
  33. FPS = 30
  34. SYSTEM_FONT = pygame.font.SysFont ('notosanscjkjp', 11, bold = True)
  35. USER_FONT = pygame.font.SysFont ('notosanscjkjp', 15, italic = True)
  36. DEERJIKA_FONT = pygame.font.SysFont ('07nikumarufont', 23)
  37. def main (
  38. ) -> None:
  39. game = Game ()
  40. Bg (game)
  41. balloon = Balloon (game)
  42. deerjika = Deerjika (game, DeerjikaPattern.RELAXED,
  43. x = CWindow.WIDTH * 3 / 4,
  44. y = CWindow.HEIGHT - 56.25,
  45. balloon = balloon)
  46. snack_time = SnackTime (game)
  47. CurrentTime (game, DEERJIKA_FONT)
  48. try:
  49. broadcast = Broadcast (os.environ['BROADCAST_CODE'])
  50. except Exception:
  51. pass
  52. waiting_balloon = (False, '', '')
  53. while True:
  54. for event in pygame.event.get ():
  55. if event.type == pygame.QUIT:
  56. pygame.quit ()
  57. sys.exit ()
  58. if (not balloon.enabled) and (not snack_time.enabled):
  59. if waiting_balloon[0]:
  60. deerjika.talk (waiting_balloon[1], waiting_balloon[2])
  61. waiting_balloon = (False, '', '')
  62. try:
  63. DB.begin_transaction ()
  64. answer_flags = (AnsweredFlag.where ('platform', Platform.YOUTUBE.value)
  65. .where ('answered', False)
  66. .get ())
  67. if answer_flags:
  68. answer_flag = random.choice (answer_flags)
  69. answer = Answer.find (answer_flag.answer_id)
  70. match QueryType (answer.query_rel.query_type):
  71. case QueryType.YOUTUBE_COMMENT:
  72. query = Query.find (answer.query_id)
  73. deerjika.talk (query.content, answer.content)
  74. answer_flag.answered = True
  75. answer_flag.save ()
  76. case QueryType.SNACK_TIME:
  77. snack_time.play ()
  78. query = Query.find (answer.query_id)
  79. waiting_balloon = (True, query.content, answer.content)
  80. answer_flag.answered = True
  81. answer_flag.save ()
  82. DB.commit ()
  83. add_query (broadcast)
  84. except Exception as ex:
  85. print (ex)
  86. game.redraw ()
  87. class Bg:
  88. """
  89. 背景オブゼクト管理用クラス
  90. Attributes:
  91. base (BgBase): 最背面
  92. grass (BgGrass): 草原部分
  93. jojoko (Jojoko): 大月ヨヨコ
  94. kita (KitaSun): き太く陽
  95. """
  96. base: BgBase
  97. grass: BgGrass
  98. jojoko: Jojoko
  99. kita: KitaSun
  100. def __init__ (
  101. self,
  102. game: Game,
  103. ):
  104. self.kita = KitaSun (game)
  105. self.base = BgBase (game, self.kita.sun, layer = self.kita.layer - 5)
  106. self.jojoko = Jojoko (game)
  107. self.grass = BgGrass (game)
  108. class DeerjikaPattern (Enum):
  109. """
  110. ニジカの状態
  111. Members:
  112. NORMAL: 通常
  113. RELAXED: 足パタパタ
  114. SLEEPING: 寝ニジカ
  115. DANCING: ダンシング・ニジカ
  116. """
  117. NORMAL = auto ()
  118. RELAXED = auto ()
  119. SLEEPING = auto ()
  120. DANCING = auto ()
  121. class Direction (Enum):
  122. """
  123. クリーチャの向き
  124. Members:
  125. LEFT: 左向き
  126. RIGHT: 右向き
  127. """
  128. LEFT = auto ()
  129. RIGHT = auto ()
  130. class Game:
  131. """
  132. ゲーム・クラス
  133. Attributes:
  134. clock (Clock): Clock オブゼクト
  135. frame (int): フレーム・カウンタ
  136. last_answered_at (datetime): 最後に回答した時刻
  137. now (datetime): 基準日時
  138. objects (list[GameObject]): 再描画するクラスのリスト
  139. screen (Surface): 基底スクリーン
  140. sky (Sky): 天体情報
  141. """
  142. bgm: Sound
  143. clock: Clock
  144. fps: float
  145. frame: int
  146. last_answered_at: datetime
  147. now: datetime
  148. objects: list[GameObject]
  149. screen: Surface
  150. sky: Sky
  151. def __init__ (
  152. self,
  153. ):
  154. self.now = datetime.now ()
  155. self.screen = pygame.display.set_mode ((CWindow.WIDTH, CWindow.HEIGHT))
  156. self.clock = Clock ()
  157. self.fps = FPS
  158. self.frame = 0
  159. self.objects = []
  160. self.bgm = Sound ('./assets/bgm.mp3')
  161. self.bgm.set_volume (.15)
  162. self.bgm.play (loops = -1)
  163. self._create_sky ()
  164. def redraw (
  165. self,
  166. ) -> None:
  167. self.now = datetime.now ()
  168. self.sky.observer.date = self.now - timedelta (hours = 9)
  169. for obj in sorted (self.objects, key = lambda obj: obj.layer):
  170. if obj.enabled:
  171. obj.redraw ()
  172. pygame.display.update ()
  173. delta_time = self.clock.tick (FPS) / 1000
  174. self.fps = 1 / delta_time
  175. if delta_time > 1 / FPS:
  176. for _ in range (int (FPS * delta_time) - 1):
  177. for obj in self.objects:
  178. if obj.enabled:
  179. obj.update ()
  180. def _create_sky (
  181. self,
  182. ) -> None:
  183. self.sky = Sky ()
  184. self.sky.observer = Observer ()
  185. self.sky.observer.lat = '35'
  186. self.sky.observer.lon = '139'
  187. class GameObject:
  188. """
  189. 各ゲーム・オブゼクトの基底クラス
  190. Attributes:
  191. arg (float): 回転角度 (rad)
  192. ax (float): X 軸に対する加速度 (px/frame^2)
  193. ay (float): y 軸に対する加速度 (px/frame^2)
  194. enabled (bool): オブゼクトの表示可否
  195. frame (int): フレーム・カウンタ
  196. game (Game): ゲーム基盤
  197. height (int): 高さ (px)
  198. vx (float): x 軸に対する速度 (px/frame)
  199. vy (float): y 軸に対する速度 (px/frame)
  200. width (int): 幅 (px)
  201. x (float): X 座標 (px)
  202. y (float): Y 座標 (px)
  203. """
  204. arg: float = 0
  205. ax: float = 0
  206. ay: float = 0
  207. enabled: bool = True
  208. frame: int
  209. game: Game
  210. height: int
  211. layer: float
  212. vx: float = 0
  213. vy: float = 0
  214. width: int
  215. x: float
  216. y: float
  217. def __init__ (
  218. self,
  219. game: Game,
  220. layer: float | None = None,
  221. enabled: bool = True,
  222. x: float = 0,
  223. y: float = 0,
  224. ):
  225. self.game = game
  226. self.enabled = enabled
  227. self.frame = 0
  228. if layer is None:
  229. if self.game.objects:
  230. layer = max (obj.layer for obj in self.game.objects) + 10
  231. else:
  232. layer = 0
  233. self.layer = layer
  234. self.x = x
  235. self.y = y
  236. self.game.objects.append (self)
  237. def redraw (
  238. self,
  239. ) -> None:
  240. self.update ()
  241. def update (
  242. self,
  243. ) -> None:
  244. self.x += self.vx
  245. self.y += self.vy
  246. self.vx += self.ax
  247. self.vy += self.ay
  248. self.frame += 1
  249. class BgBase (GameObject):
  250. """
  251. 背景
  252. Attributes:
  253. surface (Surface): 背景 Surface
  254. """
  255. bg: Surface
  256. bg_evening: Surface
  257. bg_grass: Surface
  258. bg_night: Surface
  259. sun: Sun
  260. def __init__ (
  261. self,
  262. game: Game,
  263. sun: Sun,
  264. layer: float,
  265. ):
  266. super ().__init__ (game, layer = layer)
  267. self.bg = self._load_image ('./assets/bg.jpg')
  268. self.bg_evening = self._load_image ('./assets/bg-evening.jpg')
  269. self.bg_grass = self._load_image ('./assets/bg-grass.png')
  270. self.bg_night = self._load_image ('./assets/bg-night.jpg')
  271. self.sun = sun
  272. @staticmethod
  273. def _load_image (
  274. path: str,
  275. ) -> Surface:
  276. return pygame.transform.scale (pygame.image.load (path),
  277. (CWindow.WIDTH, CWindow.HEIGHT))
  278. def redraw (
  279. self,
  280. ) -> None:
  281. date_tmp = self.game.sky.observer.date
  282. self.game.sky.observer.date = self.game.now.date ()
  283. sunrise_start: datetime = (
  284. (ephem.localtime (self.game.sky.observer.previous_rising (self.sun))
  285. - timedelta (minutes = 30)))
  286. sunrise_end: datetime = sunrise_start + timedelta (hours = 1)
  287. sunrise_centre: datetime = (
  288. sunrise_start + (sunrise_end - sunrise_start) / 2)
  289. sunset_start: datetime = (
  290. (ephem.localtime (self.game.sky.observer.next_setting (self.sun))
  291. - timedelta (minutes = 30)))
  292. sunset_end: datetime = sunset_start + timedelta (hours = 1)
  293. sunset_centre: datetime = (
  294. sunset_start + (sunset_end - sunset_start) / 2)
  295. self.game.sky.observer.date = date_tmp
  296. surface: Surface = ((self.bg
  297. if (sunrise_centre <= self.game.now < sunset_centre)
  298. else self.bg_night)
  299. .copy ())
  300. if sunrise_start <= self.game.now < sunrise_end:
  301. self.bg_evening.set_alpha (255 - int ((abs (self.game.now - sunrise_centre) * 510)
  302. / (sunrise_end - sunrise_centre)))
  303. elif sunset_start <= self.game.now < sunset_end:
  304. self.bg_evening.set_alpha (255 - int ((abs (self.game.now - sunset_centre) * 510)
  305. / (sunset_end - sunset_centre)))
  306. else:
  307. self.bg_evening.set_alpha (0)
  308. surface.blit (self.bg_evening, (0, 0))
  309. self.game.screen.blit (surface, (self.x, self.y))
  310. super ().redraw ()
  311. class BgGrass (GameObject):
  312. """
  313. 背景の草原部分
  314. Attributes:
  315. surface (Surface): 草原 Surface
  316. """
  317. surface: Surface
  318. def __init__ (
  319. self,
  320. game: Game,
  321. ):
  322. super ().__init__ (game)
  323. self.game = game
  324. self.surface = pygame.image.load ('./assets/bg-grass.png')
  325. self.surface = pygame.transform.scale (self.surface, (CWindow.WIDTH, CWindow.HEIGHT))
  326. def redraw (
  327. self,
  328. ) -> None:
  329. self.game.screen.blit (self.surface, (self.x, self.y))
  330. super ().redraw ()
  331. class Creature (GameObject):
  332. sound: Sound
  333. def bell (
  334. self,
  335. ) -> None:
  336. self.sound.play ()
  337. class Deerjika (Creature):
  338. """
  339. 伊地知ニジカ
  340. Attributes:
  341. height (int): 高さ (px)
  342. scale (float): 拡大率
  343. surfaces (list[Surface]): ニジカの各フレームを Surface にしたリスト
  344. width (int): 幅 (px)
  345. """
  346. FPS = 30
  347. height: int
  348. scale: float = 1
  349. surfaces: list[Surface]
  350. width: int
  351. talking: bool = False
  352. wav: bytearray | None = None
  353. balloon: Balloon
  354. def __init__ (
  355. self,
  356. game: Game,
  357. pattern: DeerjikaPattern = DeerjikaPattern.NORMAL,
  358. direction: Direction = Direction.LEFT,
  359. layer: float | None = None,
  360. x: float = 0,
  361. y: float = 0,
  362. balloon: Balloon | None = None,
  363. ):
  364. if balloon is None:
  365. raise Exception
  366. super ().__init__ (game, layer, x = x, y = y)
  367. self.pattern = pattern
  368. self.direction = direction
  369. self.balloon = balloon
  370. match pattern:
  371. case DeerjikaPattern.NORMAL:
  372. ...
  373. case DeerjikaPattern.RELAXED:
  374. match direction:
  375. case Direction.LEFT:
  376. self.width = 480
  377. self.height = 270
  378. surface = pygame.image.load ('./assets/deerjika_relax_left.png')
  379. self.surfaces = []
  380. for x in range (0, surface.get_width (), self.width):
  381. self.surfaces.append (
  382. surface.subsurface (x, 0, self.width, self.height))
  383. case Direction.RIGHT:
  384. ...
  385. self.sound = Sound ('./assets/noon.wav')
  386. def redraw (
  387. self,
  388. ) -> None:
  389. surface = pygame.transform.scale (self.surfaces[self.frame * self.FPS // FPS
  390. % len (self.surfaces)],
  391. (self.width * self.scale, self.height * self.scale))
  392. self.game.screen.blit (surface, surface.get_rect (center = (self.x, self.y)))
  393. super ().redraw ()
  394. def update (
  395. self,
  396. ) -> None:
  397. if (not self.balloon.enabled) and self.talking:
  398. self.talking = False
  399. if (self.balloon.enabled and self.balloon.frame >= FPS * 1.5
  400. and not self.talking):
  401. self.read_out ()
  402. super ().update ()
  403. def talk (
  404. self,
  405. query: str,
  406. answer: str,
  407. ) -> None:
  408. self.bell ()
  409. self._create_wav (answer)
  410. length = 300
  411. if self.wav is not None:
  412. with wave.open ('./nizika_talking.wav', 'rb') as f:
  413. length = int (FPS * (f.getnframes () / f.getframerate () + 4))
  414. self.balloon.talk (query, answer, length = length)
  415. def read_out (
  416. self,
  417. ) -> None:
  418. try:
  419. Sound ('./nizika_talking.wav').play ()
  420. except Exception:
  421. pass
  422. self.talking = True
  423. def _create_wav (
  424. self,
  425. message: str,
  426. ) -> None:
  427. try:
  428. self.wav = Aques.main (message, False)
  429. except Exception:
  430. self.wav = None
  431. if self.wav is None:
  432. return
  433. with open ('./nizika_talking.wav', 'wb') as f:
  434. f.write (self.wav)
  435. class CurrentTime (GameObject):
  436. """
  437. 現在日時表示
  438. Attributes:
  439. font (Font): フォント
  440. """
  441. font: Font
  442. def __init__ (
  443. self,
  444. game: Game,
  445. font: Font,
  446. ):
  447. super ().__init__ (game)
  448. self.font = font
  449. def redraw (
  450. self,
  451. ) -> None:
  452. for i in range (2):
  453. cl = (i * 255, i * 255, i * 255)
  454. self.game.screen.blit (self.font.render (str (self.game.now), True, cl), (-i, -i))
  455. self.game.screen.blit (self.font.render ('%2.3f fps' % self.game.fps, True, cl), (-i, 24 - i))
  456. super ().redraw ()
  457. class Balloon (GameObject):
  458. """
  459. 吹出し
  460. Attributes:
  461. answer (str): 回答テキスト
  462. image_url (str, None): 画像 URL
  463. length (int): 表示する時間 (frame)
  464. query (str): 質問テキスト
  465. surface (Surface): 吹出し Surface
  466. x_flip (bool): 左右反転フラグ
  467. y_flip (bool): 上下反転フラグ
  468. """
  469. answer: str = ''
  470. image_url: str | None = None
  471. length: int = 300
  472. query: str = ''
  473. surface: Surface
  474. x_flip: bool = False
  475. y_flip: bool = False
  476. def __init__ (
  477. self,
  478. game: Game,
  479. x_flip: bool = False,
  480. y_flip: bool = False,
  481. ):
  482. super ().__init__ (game, enabled = False)
  483. self.x_flip = x_flip
  484. self.y_flip = y_flip
  485. self.surface = pygame.transform.scale (pygame.image.load ('./assets/balloon.png'),
  486. (CWindow.WIDTH, CWindow.HEIGHT / 2))
  487. self.surface = pygame.transform.flip (self.surface, self.x_flip, self.y_flip)
  488. def redraw (
  489. self,
  490. ) -> None:
  491. if self.frame >= self.length:
  492. self.enabled = False
  493. self.game.last_answered_at = self.game.now
  494. return
  495. query = self.query
  496. if CommonModule.len_by_full (query) > 21:
  497. query = CommonModule.mid_by_full (query, 0, 19.5) + '...'
  498. answer = Surface ((375, ((CommonModule.len_by_full (self.answer) - 1) // 16 + 1) * 23.4375),
  499. pygame.SRCALPHA)
  500. for i in range (int (CommonModule.len_by_full (self.answer) - 1) // 16 + 1):
  501. answer.blit (DEERJIKA_FONT.render (
  502. CommonModule.mid_by_full (self.answer, 16 * i, 16), True, (192, 0, 0)),
  503. (0, 23.4375 * i))
  504. surface = self.surface.copy ()
  505. surface.blit (USER_FONT.render ('>' + query, True, (0, 0, 0)), (56.25, 32.8125))
  506. y: float
  507. if self.frame < 30:
  508. y = 0
  509. elif self.frame >= self.length - 90:
  510. y = answer.get_height () - 46.875
  511. else:
  512. y = int ((answer.get_height () - 46.875) * (self.frame - 30) / (self.length - 120))
  513. surface.blit (answer, (46.875, 70.3125), Rect (0, y, 375, 46.875))
  514. self.game.screen.blit (surface, (0, 0))
  515. super ().redraw ()
  516. def talk (
  517. self,
  518. query: str,
  519. answer: str,
  520. image_url: str | None = None,
  521. length: int = 300,
  522. ) -> None:
  523. self.query = query
  524. self.answer = answer
  525. self.image_url = image_url
  526. self.length = length
  527. self.frame = 0
  528. self.enabled = True
  529. class KitaSun (GameObject):
  530. """
  531. き太く陽
  532. Attributes:
  533. sun (Sun): ephem の太陽オブゼクト
  534. surface (Surface): き太く陽 Surface
  535. """
  536. alt: float
  537. az: float
  538. sun: Sun
  539. surface: Surface
  540. def __init__ (
  541. self,
  542. game: Game,
  543. ):
  544. super ().__init__ (game)
  545. self.surface = pygame.transform.scale (pygame.image.load ('./assets/sun.png'), (93.75, 93.75))
  546. self.sun = Sun ()
  547. def redraw (
  548. self,
  549. ) -> None:
  550. surface = pygame.transform.rotate (self.surface, -(90 + math.degrees (self.arg)))
  551. self.game.screen.blit (surface, surface.get_rect (center = (self.x, self.y)))
  552. super ().redraw ()
  553. def update (
  554. self,
  555. ) -> None:
  556. self.sun.compute (self.game.sky.observer)
  557. self.alt = self.sun.alt
  558. self.az = self.sun.az
  559. if abs (self.new_arg - self.arg) > math.radians (15):
  560. self.arg = self.new_arg
  561. self.x = self.new_x
  562. self.y = self.new_y
  563. super ().update ()
  564. @property
  565. def new_x (
  566. self,
  567. ) -> float:
  568. return CWindow.WIDTH * (math.degrees (self.az) - 80) / 120
  569. @property
  570. def new_y (
  571. self,
  572. ) -> float:
  573. return ((CWindow.HEIGHT / 2)
  574. - ((CWindow.HEIGHT / 2 + 46.875) * math.sin (self.alt)
  575. / math.sin (math.radians (60))))
  576. @property
  577. def new_arg (
  578. self,
  579. ) -> float:
  580. return math.atan2 (self.new_y - self.y, self.new_x - self.x)
  581. class Jojoko (GameObject):
  582. """
  583. 大月ヨヨコ
  584. Attributes:
  585. base (Surface): 満月ヨヨコ Surface
  586. moon (Moon): ephem の月オブゼクト
  587. surface (Surface): 缺けたヨヨコ
  588. """
  589. alt: float
  590. az: float
  591. base: Surface
  592. moon: Moon
  593. surface: Surface
  594. def __init__ (
  595. self,
  596. game: Game,
  597. ):
  598. super ().__init__ (game)
  599. self.base = pygame.transform.scale (pygame.image.load ('./assets/moon.png'), (93.75, 93.75))
  600. self.moon = Moon ()
  601. self.surface = self._get_surface ()
  602. def redraw (
  603. self,
  604. ) -> None:
  605. self.moon.compute (self.game.sky.observer)
  606. self.alt = self.moon.alt
  607. self.az = self.moon.az
  608. if abs (self.new_arg - self.arg) > math.radians (15):
  609. self.arg = self.new_arg
  610. self.x = self.new_x
  611. self.y = self.new_y
  612. if self.frame % (FPS * 3600) == 0:
  613. self.surface = self._get_surface ()
  614. surface = pygame.transform.rotate (self.surface, -(90 + math.degrees (self.arg)))
  615. surface.set_colorkey ((0, 255, 0))
  616. self.game.screen.blit (surface, surface.get_rect (center = (self.x, self.y)))
  617. super ().redraw ()
  618. @property
  619. def phase (
  620. self,
  621. ) -> float:
  622. dt: datetime = ephem.localtime (ephem.previous_new_moon (self.game.sky.observer.date))
  623. return (self.game.now - dt).total_seconds () / 60 / 60 / 24
  624. def _get_surface (
  625. self,
  626. ) -> Surface:
  627. """
  628. ヨヨコを月齢に応じて缺かす.
  629. Returns:
  630. Surface: 缺けたヨヨコ
  631. """
  632. jojoko = self.base.copy ()
  633. for i in range (200):
  634. if 1 <= self.phase < 15:
  635. pygame.gfxdraw.bezier (jojoko, ((0, (100 + i) * .468_75), (46.875, (180 * self.phase / 7 - 80 + i) * .468_75), (93.75, (100 + i) * .468_75)), 3, (0, 255, 0))
  636. elif self.phase < 16:
  637. pass
  638. elif self.phase < 30:
  639. pygame.gfxdraw.bezier (jojoko, ((0, (100 - i) * .468_75), (46.875, (180 * (self.phase - 15) / 7 - 80 - i) * .468_75), (93.75, (100 - i) * .468_75)), 3, (0, 255, 0))
  640. else:
  641. jojoko.fill ((0, 255, 0))
  642. return jojoko
  643. @property
  644. def new_x (
  645. self,
  646. ) -> float:
  647. return CWindow.WIDTH * (math.degrees (self.az) - 80) / 120
  648. @property
  649. def new_y (
  650. self,
  651. ) -> float:
  652. return ((CWindow.HEIGHT / 2)
  653. - ((CWindow.HEIGHT / 2 + 46.875) * math.sin (self.alt)
  654. / math.sin (math.radians (60))))
  655. @property
  656. def new_arg (
  657. self,
  658. ) -> float:
  659. return math.atan2 (self.new_y - self.y, self.new_x - self.x)
  660. class Sky:
  661. """
  662. 天体に関する情報を保持するクラス
  663. Attributes:
  664. observer (Observer): 観測値
  665. """
  666. observer: Observer
  667. class CWindow:
  668. """
  669. ウィンドゥに関する定数クラス
  670. Attributes:
  671. WIDTH (int): ウィンドゥ幅
  672. HEIGHT (int): ウィンドゥ高さ
  673. """
  674. WIDTH = 480
  675. HEIGHT = 360
  676. class Broadcast:
  677. chat: PytchatCore
  678. code: str
  679. def __init__ (
  680. self,
  681. broadcast_code,
  682. ):
  683. self.code = broadcast_code
  684. self.chat = pytchat.create (self.code)
  685. def fetch_chat (
  686. self,
  687. ) -> Chat | None:
  688. if not self.chat.is_alive ():
  689. self.chat = pytchat.create (self.code)
  690. return None
  691. chats = self.chat.get ().items
  692. if not chats:
  693. return None
  694. return random.choice (chats)
  695. class Video (GameObject):
  696. fps: int
  697. pausing: bool = False
  698. sound: Sound | None
  699. surfaces: list[Surface]
  700. def __init__ (
  701. self,
  702. game: Game,
  703. path: str,
  704. ):
  705. super ().__init__ (game)
  706. self.pausing = False
  707. (self.surfaces, self.fps) = self._create_surfaces (path)
  708. self.sound = self._create_sound (path)
  709. self.stop ()
  710. def _create_sound (
  711. self,
  712. path: str,
  713. ) -> Sound | None:
  714. bytes_io = BytesIO ()
  715. try:
  716. from pydub import AudioSegment
  717. audio = AudioSegment.from_file (path, format = path.split ('.')[-1])
  718. except ModuleNotFoundError:
  719. return None
  720. audio.export (bytes_io, format = 'wav')
  721. bytes_io.seek (0)
  722. return pygame.mixer.Sound (bytes_io)
  723. def _create_surfaces (
  724. self,
  725. path: str,
  726. ) -> tuple[list[Surface], int]:
  727. cap = self._load (path)
  728. surfaces: list[Surface] = []
  729. if cap is None:
  730. return ([], FPS)
  731. fps = int (cap.get (cv2.CAP_PROP_FPS))
  732. while cap.isOpened ():
  733. frame = self._read_frame (cap)
  734. if frame is None:
  735. break
  736. surfaces.append (self._convert_to_surface (frame))
  737. new_surfaces: list[Surface] = []
  738. for i in range (len (surfaces) * FPS // fps):
  739. new_surfaces.append (surfaces[i * fps // FPS])
  740. return (new_surfaces, fps)
  741. def _load (
  742. self,
  743. path: str,
  744. ) -> VideoCapture | None:
  745. """
  746. OpenCV で動画を読込む.
  747. """
  748. cap = VideoCapture (path)
  749. if cap.isOpened ():
  750. return cap
  751. return None
  752. def _read_frame (
  753. self,
  754. cap: VideoCapture,
  755. ) -> np.ndarray | None:
  756. """
  757. 動画のフレームを読込む.
  758. """
  759. ret: bool
  760. frame: np.ndarray
  761. (ret, frame) = cap.read ()
  762. if ret:
  763. return frame
  764. return None
  765. def _convert_to_surface (
  766. self,
  767. frame: np.ndarray,
  768. ) -> Surface:
  769. frame = cv2.cvtColor (frame, cv2.COLOR_BGR2RGB)
  770. frame_surface = pygame.surfarray.make_surface (frame)
  771. frame_surface = pygame.transform.rotate (frame_surface, -90)
  772. frame_surface = pygame.transform.flip (frame_surface, True, False)
  773. return frame_surface
  774. def play (
  775. self,
  776. ) -> None:
  777. self.enabled = True
  778. self.pausing = False
  779. if self.sound is not None:
  780. self.sound.play ()
  781. def stop (
  782. self,
  783. ) -> None:
  784. self.enabled = False
  785. self.frame = 0
  786. def pause (
  787. self,
  788. ) -> None:
  789. self.pausing = True
  790. def redraw (
  791. self,
  792. ) -> None:
  793. surface = pygame.transform.scale (self.surfaces[self.frame], (self.width, self.height))
  794. self.game.screen.blit (surface, (self.x, self.y))
  795. super ().redraw ()
  796. def update (
  797. self,
  798. ) -> None:
  799. if self.frame >= len (self.surfaces) - 1:
  800. self.stop ()
  801. if self.pausing:
  802. self.frame -= 1
  803. super ().update ()
  804. class NicoVideo (Video):
  805. ...
  806. class SnackTime (Video):
  807. def __init__ (
  808. self,
  809. game: Game,
  810. ):
  811. super ().__init__ (game, './assets/snack_time.mp4')
  812. (self.width, self.height) = (CWindow.HEIGHT * 16 // 9, CWindow.HEIGHT)
  813. (self.x, self.y) = ((CWindow.WIDTH - self.width) / 2, 0)
  814. def fetch_bytes_from_url (
  815. url: str,
  816. ) -> bytes | None:
  817. res = requests.get (url, timeout = 60)
  818. if res.status_code != 200:
  819. return None
  820. return res.content
  821. def add_query (
  822. broadcast: Broadcast,
  823. ) -> None:
  824. chat = broadcast.fetch_chat ()
  825. if chat is None:
  826. return
  827. DB.begin_transaction ()
  828. chat.message = emoji.emojize (chat.message)
  829. user = (User.where ('platform', Platform.YOUTUBE.value)
  830. .where ('code', chat.author.channelId)
  831. .first ())
  832. if user is None:
  833. user = User ()
  834. user.platform = Platform.YOUTUBE.value
  835. user.code = chat.author.channelId
  836. user.name = chat.author.name
  837. user.icon = fetch_bytes_from_url (chat.author.imageUrl)
  838. user.save ()
  839. query = Query ()
  840. query.user_id = user.id
  841. query.target_character = Character.DEERJIKA.value
  842. query.content = chat.message
  843. query.query_type = QueryType.YOUTUBE_COMMENT.value
  844. query.model = GPTModel.GPT3_TURBO.value
  845. query.sent_at = datetime.now ()
  846. query.answered = False
  847. query.save ()
  848. DB.commit ()
  849. if __name__ == '__main__':
  850. main ()