Spaces:
Sleeping
Sleeping
Sasha commited on
Commit ·
e98099c
1
Parent(s): fe2d35c
feat: add backfill resume support and session/retry fixes for VODs
Browse filesFiles changed (5)
- local_worker/role_backfiller.py+106-97
- local_worker/vod_backfiller.py+163-98
- local_worker/worker.py+16-16
- server/db.js+82
- server/server.js+21-1
101 unmodified lines102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208101 unmodified linestotal_messages = 0MAX_RETRIES = 5while True:payload = {"operationName": "VideoCommentsByOffsetOrCursor","variables": {"videoID": str(vod_id),"contentOffsetSeconds": current_offset},"extensions": {"persistedQuery": {"version": 1,"sha256Hash": "b70a3591ff0f4e0313d126c6a1502d79a1c02baebb288227c582044aa76adf6a"}}}success = Falsefor attempt in range(MAX_RETRIES):try:res = requests.post(url, json=payload, headers=gql_headers, timeout=15)if res.status_code != 200:breakdata = res.json()if isinstance(data, list):data = data[0]video = data.get("data", {}).get("video", {})if not video:return list(roles_dict.values()) # VOD ended or not foundedges = (video.get("comments") or {}).get("edges") or []if not edges:return list(roles_dict.values()) # Reached endfor edge in edges:if not edge:continuenode = edge.get("node")if not node:continuecommenter = node.get("commenter")if not commenter:continueuser = commenter.get("login")if not user:continuedisplay_name = commenter.get("displayName", user)message = node.get("message")if not message:continuetimestamp = node.get("createdAt")user_badges = message.get("userBadges") or []badges = [b.get("setID") for b in user_badges if b]# Debug: print first badge encounter to verify GQL structureif total_messages < 3 and user_badges:print(f"\n [DEBUG] userBadges raw: {user_badges}")print(f" [DEBUG] parsed badges: {badges}")is_mod = "moderator" in badges or "broadcaster" in badgesis_sub = "subscriber" in badges or "founder" in badgesis_vip = "vip" in badges# Only store users who have at least one badgeif is_mod or is_sub or is_vip:roles_dict[user.lower()] = {"username": user,"displayName": display_name,"isMod": is_mod,"isSub": is_sub,"isVip": is_vip,"timestamp": timestamp}total_messages += 1print(f" -> Обработано {total_messages} сообщений, найдено {len(roles_dict)} уникальных пользователей...", end="\r")last_offset = edges[-1].get("node", {}).get("contentOffsetSeconds")if last_offset is not None:next_offset = last_offset + 1if next_offset <= current_offset:next_offset = current_offset + 30current_offset = next_offsetelse:return list(roles_dict.values())success = Truebreak # Success — go to next pageexcept Exception as e:wait = 2 ** attempt # 1, 2, 4, 8, 16 secondsprint(f"\n [!] Ошибка (попытка {attempt+1}/{MAX_RETRIES}): {e}")if attempt < MAX_RETRIES - 1:print(f" [!] Повтор через {wait}с...")time.sleep(wait)if not success:print(f"\n [!] Не удалось получить данные после {MAX_RETRIES} попыток. Останавливаемся на offset={current_offset}.")breakreturn list(roles_dict.values())101 unmodified lines102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217101 unmodified linestotal_messages = 0MAX_RETRIES = 5with requests.Session() as session:while True:payload = {"operationName": "VideoCommentsByOffsetOrCursor","variables": {"videoID": str(vod_id),"contentOffsetSeconds": current_offset},"extensions": {"persistedQuery": {"version": 1,"sha256Hash": "b70a3591ff0f4e0313d126c6a1502d79a1c02baebb288227c582044aa76adf6a"}}}success = Falsefor attempt in range(MAX_RETRIES):try:res = session.post(url, json=payload, headers=gql_headers, timeout=15)if res.status_code == 429:wait = 2 ** attemptprint(f"\n [!] Rate limited (429). Повтор через {wait}с...")time.sleep(wait)continueif res.status_code != 200:print(f"\n [!] Ошибка GQL статус {res.status_code}")breakdata = res.json()if isinstance(data, list):data = data[0]video = data.get("data", {}).get("video", {})if not video:return list(roles_dict.values()) # VOD ended or not foundedges = (video.get("comments") or {}).get("edges") or []if not edges:return list(roles_dict.values()) # Reached endfor edge in edges:if not edge:continuenode = edge.get("node")if not node:continuecommenter = node.get("commenter")if not commenter:continueuser = commenter.get("login")if not user:continuedisplay_name = commenter.get("displayName", user)message = node.get("message")if not message:continuetimestamp = node.get("createdAt")user_badges = message.get("userBadges") or []badges = [b.get("setID") for b in user_badges if b]# Debug: print first badge encounter to verify GQL structureif total_messages < 3 and user_badges:print(f"\n [DEBUG] userBadges raw: {user_badges}")print(f" [DEBUG] parsed badges: {badges}")is_mod = "moderator" in badges or "broadcaster" in badgesis_sub = "subscriber" in badges or "founder" in badgesis_vip = "vip" in badges# Only store users who have at least one badgeif is_mod or is_sub or is_vip:roles_dict[user.lower()] = {"username": user,"displayName": display_name,"isMod": is_mod,"isSub": is_sub,"isVip": is_vip,"timestamp": timestamp}total_messages += 1print(f" -> Обработано {total_messages} сообщений, найдено {len(roles_dict)} уникальных пользователей...", end="\r")last_offset = edges[-1].get("node", {}).get("contentOffsetSeconds")if last_offset is not None:next_offset = last_offset + 1if next_offset <= current_offset:next_offset = current_offset + 30current_offset = next_offsetelse:return list(roles_dict.values())# Tiny sleep to avoid aggressive spammingtime.sleep(0.1)success = Truebreak # Success — go to next pageexcept Exception as e:wait = 2 ** attempt # 1, 2, 4, 8, 16 secondsprint(f"\n [!] Ошибка (попытка {attempt+1}/{MAX_RETRIES}): {e}")if attempt < MAX_RETRIES - 1:print(f" [!] Повтор через {wait}с...")time.sleep(wait)if not success:print(f"\n [!] Не удалось получить данные после {MAX_RETRIES} попыток. Останавливаемся на offset={current_offset}.")breakreturn list(roles_dict.values())
94 unmodified lines9596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202173 unmodified lines37637737837938038138238310 unmodified lines3943953963973983994005 unmodified lines40640740840941041141294 unmodified linescurrent_offset = start_offsetprint(f"\n[Chat] Запуск скачивания чата для VOD {vod_id} с секунды {start_offset} до {'конца' if end_offset is None else str(end_offset) + 's'}...")while True:if end_offset is not None and current_offset >= end_offset:print(f"\n[Chat] Достигнут конечный офсет {end_offset}s. Завершаем скачивание чата.")breakpayload = {"operationName": "VideoCommentsByOffsetOrCursor","variables": {"videoID": str(vod_id),"contentOffsetSeconds": current_offset},"extensions": {"persistedQuery": {"version": 1,"sha256Hash": "b70a3591ff0f4e0313d126c6a1502d79a1c02baebb288227c582044aa76adf6a"}}}try:res = requests.post(url, json=payload, headers=gql_headers, timeout=10)if res.status_code != 200:print(f"[Chat] Ошибка GQL: {res.status_code}")breakdata = res.json()if isinstance(data, list):data = data[0]video = data.get("data", {}).get("video", {})if not video:breakcomments_edge = video.get("comments") or {}edges = comments_edge.get("edges") or []if not edges:breakfor edge in edges:if not edge:continuenode = edge.get("node")if not node:continuemsg_id = node.get("id")if not msg_id or msg_id in seen_ids:continuecommenter = node.get("commenter")if not commenter:continueuser = commenter.get("login")if not user:continuedisplay_name = commenter.get("displayName", user)message = node.get("message")if not message:continuefragments = message.get("fragments") or []message_text = "".join([f.get("text", "") for f in fragments if f])timestamp = node.get("createdAt")# Badges parseuser_badges = message.get("userBadges") or []badges = [b.get("setID") for b in user_badges if b]is_mod = "moderator" in badges or "broadcaster" in badgesis_sub = "subscriber" in badges or "founder" in badgesis_vip = "vip" in badgesis_streamer = (user.lower() == TWITCH_CHANNEL)seen_ids.add(msg_id)comments.append({"id": msg_id,"username": user,"displayName": display_name,"message": message_text,"timestamp": timestamp,"isStreamer": is_streamer,"isMod": is_mod,"isSub": is_sub,"isVip": is_vip})print(f"-> Загружено {len(comments)} комментариев...", end="\r")# Progress offsetlast_offset = edges[-1].get("node", {}).get("contentOffsetSeconds")if last_offset is not None:next_offset = last_offset + 1if next_offset <= current_offset:next_offset = current_offset + 30current_offset = next_offsetelse:breakexcept Exception as e:print(f"\n[Chat] Ошибка при загрузке: {e}")breakprint(f"\n[Chat] Загрузка завершена. Всего сообщений: {len(comments)}")return comments173 unmodified linesprint(f"[Error] Ошибка сети при обращении к бэкенду: {e}")sys.exit(1)# 3. Download and Upload Chat commentschat_comments = download_vod_chat(vod_id)if chat_comments:print("\n[Sync] Отправка чата на сервер (пакетами по 100 сообщений)...")batch_size = 10010 unmodified linesprint(f"\n-> Ошибка сети при отправке пакета: {e}")print("\n-> Синхронизация чата успешно завершена!")# 4. Transcribe Audiotranscribe_confirm = input("\nХотите запустить скачивание и транскрибацию аудиодорожки (Whisper)? (y/n): ").strip().lower()if transcribe_confirm == 'y':# Init Whisper5 unmodified linescompute_type=WHISPER_COMPUTE_TYPE,cpu_threads=WHISPER_CPU_THREADS)transcribe_vod_audio(vod_id, created_at, model)except Exception as e:print(f"[Whisper Error] Не удалось инициализировать Whisper: {e}")94 unmodified lines9596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224173 unmodified lines39839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744810 unmodified lines4594604614624634644655 unmodified lines47147247347447547647794 unmodified linescurrent_offset = start_offsetprint(f"\n[Chat] Запуск скачивания чата для VOD {vod_id} с секунды {start_offset} до {'конца' if end_offset is None else str(end_offset) + 's'}...")MAX_RETRIES = 5with requests.Session() as session:while True:if end_offset is not None and current_offset >= end_offset:print(f"\n[Chat] Достигнут конечный офсет {end_offset}s. Завершаем скачивание чата.")breakpayload = {"operationName": "VideoCommentsByOffsetOrCursor","variables": {"videoID": str(vod_id),"contentOffsetSeconds": current_offset},"extensions": {"persistedQuery": {"version": 1,"sha256Hash": "b70a3591ff0f4e0313d126c6a1502d79a1c02baebb288227c582044aa76adf6a"}}}success = Falsefor attempt in range(MAX_RETRIES):try:res = session.post(url, json=payload, headers=gql_headers, timeout=15)if res.status_code == 429:wait = 2 ** attemptprint(f"\n[Chat] Rate limited (429). Повтор через {wait}с...")time.sleep(wait)continueif res.status_code != 200:print(f"\n[Chat] Ошибка GQL статус {res.status_code}")breakdata = res.json()if isinstance(data, list):data = data[0]video = data.get("data", {}).get("video", {})if not video:breakcomments_edge = video.get("comments") or {}edges = comments_edge.get("edges") or []if not edges:breakfor edge in edges:if not edge:continuenode = edge.get("node")if not node:continuemsg_id = node.get("id")if not msg_id or msg_id in seen_ids:continuecommenter = node.get("commenter")if not commenter:continueuser = commenter.get("login")if not user:continuedisplay_name = commenter.get("displayName", user)message = node.get("message")if not message:continuefragments = message.get("fragments") or []message_text = "".join([f.get("text", "") for f in fragments if f])timestamp = node.get("createdAt")# Badges parseuser_badges = message.get("userBadges") or []badges = [b.get("setID") for b in user_badges if b]is_mod = "moderator" in badges or "broadcaster" in badgesis_sub = "subscriber" in badges or "founder" in badgesis_vip = "vip" in badgesis_streamer = (user.lower() == TWITCH_CHANNEL)seen_ids.add(msg_id)comments.append({"id": msg_id,"username": user,"displayName": display_name,"message": message_text,"timestamp": timestamp,"isStreamer": is_streamer,"isMod": is_mod,"isSub": is_sub,"isVip": is_vip})print(f"-> Загружено {len(comments)} комментариев...", end="\r")# Progress offsetlast_offset = edges[-1].get("node", {}).get("contentOffsetSeconds")if last_offset is not None:next_offset = last_offset + 1if next_offset <= current_offset:next_offset = current_offset + 30current_offset = next_offsetelse:break# Tiny sleep to avoid aggressive spammingtime.sleep(0.1)success = Truebreakexcept Exception as e:wait = 2 ** attemptprint(f"\n[Chat] Ошибка при загрузке (попытка {attempt+1}/{MAX_RETRIES}): {e}")if attempt < MAX_RETRIES - 1:print(f"[Chat] Повтор через {wait}с...")time.sleep(wait)if not success:print(f"\n[Chat] Не удалось продолжить скачивание из-за ошибок на offset {current_offset}.")breakprint(f"\n[Chat] Загрузка завершена. Всего сообщений: {len(comments)}")return comments173 unmodified linesprint(f"[Error] Ошибка сети при обращении к бэкенду: {e}")sys.exit(1)# 3. Check for existing backfill status (resume/append support)chat_start_offset = 0voice_start_offset = 0try:status_url = f"{API_URL}/api/streams/backfill-status?twitchStreamId=vod-{vod_id}"res = requests.get(status_url, headers=headers, timeout=5)if res.status_code == 200:status_data = res.json()# Chat checkmsg_count = status_data.get("messageCount", 0)latest_msg_ts = status_data.get("latestMessageTimestamp")if msg_count > 0 and latest_msg_ts:from datetime import datetimeclean_ts = latest_msg_ts.replace('Z', '+00:00')latest_epoch = datetime.fromisoformat(clean_ts).timestamp()clean_created = created_at.replace('Z', '+00:00')created_epoch = datetime.fromisoformat(clean_created).timestamp()diff = int(latest_epoch - created_epoch)if diff > 0:chat_start_offset = diffprint(f"[Sync] Найден существующий чат в базе ({msg_count} сообщений). Возобновляем загрузку с секунды {chat_start_offset}...")# Voice checkvoice_count = status_data.get("voiceCount", 0)latest_voice_ts = status_data.get("latestVoiceTimestamp")if voice_count > 0 and latest_voice_ts:from datetime import datetimeclean_ts = latest_voice_ts.replace('Z', '+00:00')latest_epoch = datetime.fromisoformat(clean_ts).timestamp()clean_created = created_at.replace('Z', '+00:00')created_epoch = datetime.fromisoformat(clean_created).timestamp()diff = int(latest_epoch - created_epoch)if diff > 0:voice_start_offset = (diff // 30) * 30print(f"[Sync] Найден распознанный голос в базе ({voice_count} слов). Возобновляем транскрибацию с секунды {voice_start_offset}...")except Exception as e:print(f"[Sync Warning] Не удалось получить статус дозаписи: {e}")# 4. Download and Upload Chat commentschat_comments = download_vod_chat(vod_id, start_offset=chat_start_offset)if chat_comments:print("\n[Sync] Отправка чата на сервер (пакетами по 100 сообщений)...")batch_size = 10010 unmodified linesprint(f"\n-> Ошибка сети при отправке пакета: {e}")print("\n-> Синхронизация чата успешно завершена!")# 5. Transcribe Audiotranscribe_confirm = input("\nХотите запустить скачивание и транскрибацию аудиодорожки (Whisper)? (y/n): ").strip().lower()if transcribe_confirm == 'y':# Init Whisper5 unmodified linescompute_type=WHISPER_COMPUTE_TYPE,cpu_threads=WHISPER_CPU_THREADS)transcribe_vod_audio(vod_id, created_at, model, start_offset=voice_start_offset)except Exception as e:print(f"[Whisper Error] Не удалось инициализировать Whisper: {e}")
721 unmodified lines722723724725726727125 unmodified lines853854855856857858859860861862863864865866867868869870871872873874721 unmodified linesprint(f"[Capture] Stream is LIVE! Starting audio pipeline...")# Start streamlink piping audio to ffmpeg, converting it to raw 16kHz mono 16-bit PCMstreamlink_cmd = ["streamlink", f"twitch.tv/{TWITCH_CHANNEL}", "audio,worst", "-O"]ffmpeg_cmd = ["ffmpeg", "-i", "pipe:0", "-ac", "1", "-ar", "16000", "-f", "s16le", "-"]125 unmodified linest_sender.start()t_heartbeat.start()# Notify backend that stream has started and get stream id for coveragenotify_stream_start()# Start coverage window for the active streamtry:import requests as _req_headers = {"x-api-key": API_KEY}_stream_res = _req.get(f"{API_URL}/api/streams/active", headers=_headers, timeout=5)if _stream_res.status_code == 200:_active = _stream_res.json()_sid = _active.get("stream", {}).get("id") or _active.get("id")if _sid:start_coverage(_sid, source='live')except Exception as _e:print(f"[Coverage] Could not get active stream for coverage: {_e}")# 3. Start Audio Capture (Blocks main thread)try:if CAPTURE_METHOD == "stream":721 unmodified lines722723724725726727728729730731732733734735736737738739740741742743125 unmodified lines869870871872873874721 unmodified linesprint(f"[Capture] Stream is LIVE! Starting audio pipeline...")# Notify backend that stream has started and get stream id for coveragenotify_stream_start()# Start coverage window for the active streamtry:import requests as _req_headers = {"x-api-key": API_KEY}_stream_res = _req.get(f"{API_URL}/api/streams/active", headers=_headers, timeout=5)if _stream_res.status_code == 200:_active = _stream_res.json()_sid = _active.get("stream", {}).get("id") or _active.get("id")if _sid:start_coverage(_sid, source='live')except Exception as _e:print(f"[Coverage] Could not get active stream for coverage: {_e}")# Start streamlink piping audio to ffmpeg, converting it to raw 16kHz mono 16-bit PCMstreamlink_cmd = ["streamlink", f"twitch.tv/{TWITCH_CHANNEL}", "audio,worst", "-O"]ffmpeg_cmd = ["ffmpeg", "-i", "pipe:0", "-ac", "1", "-ar", "16000", "-f", "s16le", "-"]125 unmodified linest_sender.start()t_heartbeat.start()# 3. Start Audio Capture (Blocks main thread)try:if CAPTURE_METHOD == "stream":
2021 unmodified lines2022202320242021 unmodified lines}}}2021 unmodified lines20222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062021 unmodified lines}}}/*** Get backfill status for a specific stream by its twitch_stream_id*/export async function getStreamBackfillStatus(twitchStreamId) {let stream = null;if (dbMode === 'sqlite') {stream = sqliteDb.prepare('SELECT * FROM streams WHERE twitch_stream_id = ?').get(twitchStreamId);} else {const { data, error } = await supabase.from('streams').select('*').eq('twitch_stream_id', twitchStreamId).limit(1);if (data && data.length > 0) {stream = data[0];}}if (!stream) return null;let latestMessageTimestamp = null;let latestVoiceTimestamp = null;let messageCount = 0;let voiceCount = 0;if (dbMode === 'sqlite') {const msgStats = sqliteDb.prepare('SELECT COUNT(*) as count, MAX(timestamp) as latest FROM messages WHERE stream_id = ?').get(stream.id);messageCount = msgStats.count;latestMessageTimestamp = msgStats.latest;const voiceStats = sqliteDb.prepare('SELECT COUNT(*) as count, MAX(timestamp) as latest FROM voice_words WHERE stream_id = ?').get(stream.id);voiceCount = voiceStats.count;latestVoiceTimestamp = voiceStats.latest;} else {// Supabaseconst { count: msgCount } = await supabase.from('messages').select('*', { count: 'exact', head: true }).eq('stream_id', stream.id);messageCount = msgCount || 0;if (messageCount > 0) {const { data: latestMsg } = await supabase.from('messages').select('timestamp').eq('stream_id', stream.id).order('timestamp', { ascending: false }).limit(1);if (latestMsg && latestMsg.length > 0) {latestMessageTimestamp = latestMsg[0].timestamp;}}const { count: vCount } = await supabase.from('voice_words').select('*', { count: 'exact', head: true }).eq('stream_id', stream.id);voiceCount = vCount || 0;if (voiceCount > 0) {const { data: latestVoice } = await supabase.from('voice_words').select('timestamp').eq('stream_id', stream.id).order('timestamp', { ascending: false }).limit(1);if (latestVoice && latestVoice.length > 0) {latestVoiceTimestamp = latestVoice[0].timestamp;}}}return {streamId: stream.id,twitchStreamId: stream.twitch_stream_id,messageCount,latestMessageTimestamp,voiceCount,latestVoiceTimestamp};}
38 unmodified lines39404142434445237 unmodified lines28328428528628728838 unmodified linescleanupGhostStreams,startCoverageWindow,updateCoverageHeartbeat,endCoverageWindow} from './db.js';// import { initializeEventSub } from './eventsub.js';import { cache, cacheMiddleware } from './cache.js';237 unmodified lines}});// GET list of streams missing twitch_vod_idapp.get('/api/streams/missing-vod', authenticateWorker, async (req, res) => {try {38 unmodified lines3940414243444546237 unmodified lines28428528628728828929029129229329429529629729829930030130230330430530630730838 unmodified linescleanupGhostStreams,startCoverageWindow,updateCoverageHeartbeat,endCoverageWindow,getStreamBackfillStatus} from './db.js';// import { initializeEventSub } from './eventsub.js';import { cache, cacheMiddleware } from './cache.js';237 unmodified lines}});// GET backfill status for a specific stream (chat messages count & latest timestamp, voice words count & latest timestamp)app.get('/api/streams/backfill-status', authenticateWorker, async (req, res) => {const { twitchStreamId } = req.query;if (!twitchStreamId) {return res.status(400).json({ error: 'Missing twitchStreamId query parameter' });}try {const status = await getStreamBackfillStatus(twitchStreamId);if (!status) {return res.status(404).json({ error: 'Stream not found' });}res.json(status);} catch (err) {console.error('[API Error] /api/streams/backfill-status:', err);res.status(500).json({ error: 'Internal Server Error' });}});// GET list of streams missing twitch_vod_idapp.get('/api/streams/missing-vod', authenticateWorker, async (req, res) => {try {
local_worker/role_backfiller.py+106-97
local_worker/vod_backfiller.py+163-98
local_worker/worker.py+16-16
server/db.js+82
server/server.js+21-1