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

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