bep40 commited on
Commit
47a11ab
·
verified ·
1 Parent(s): be964a5

Restore ai_runtime_fix.py from target commit 0280ca57

Browse files
Files changed (1) hide show
  1. ai_runtime_fix.py +378 -0
ai_runtime_fix.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """VNEWS Short Video Fix - standalone module with clean registration.
2
+ This module MUST be imported LAST to register /api/ai/short endpoints.
3
+ FIX v1: No route filtering issues - registers endpoints unconditionally.
4
+ """
5
+ import os
6
+ import re
7
+ import time
8
+ import json
9
+ import sys
10
+ import logging
11
+ import asyncio
12
+ import hashlib
13
+ import subprocess
14
+ import requests
15
+ from datetime import datetime, timezone, timedelta
16
+ from urllib.parse import urlparse
17
+ from fastapi import Request, Query
18
+ from fastapi.responses import JSONResponse, FileResponse
19
+
20
+ # Import dependencies
21
+ try:
22
+ import ai_ext as base
23
+ except ImportError:
24
+ import ai_runtime_final6 as base
25
+
26
+ # Try to import app from various sources
27
+ try:
28
+ from app_v2_entry import app
29
+ except ImportError:
30
+ try:
31
+ from main import app
32
+ except ImportError:
33
+ from ai_runtime_final6 import app
34
+
35
+ _log = logging.getLogger("short_fix")
36
+ _log.setLevel(logging.INFO)
37
+ if not _log.handlers:
38
+ _log.addHandler(logging.StreamHandler(sys.stderr))
39
+
40
+ DATA_DIR = "/data" if os.path.isdir("/data") else "/app/data"
41
+ os.makedirs(DATA_DIR, exist_ok=True)
42
+ SHORTS_DIR = os.path.join(DATA_DIR, "ai_shorts")
43
+ os.makedirs(SHORTS_DIR, exist_ok=True)
44
+
45
+ # ===== VIETNAMESE FONT DETECTION =====
46
+ _VN_FONT_REG = None
47
+ _VN_FONT_BOLD = None
48
+
49
+ def _get_vn_fonts():
50
+ """Find Vietnamese-supporting fonts."""
51
+ global _VN_FONT_REG, _VN_FONT_BOLD
52
+ if _VN_FONT_REG is not None:
53
+ return _VN_FONT_REG, _VN_FONT_BOLD
54
+
55
+ try:
56
+ from PIL import ImageFont
57
+ except Exception:
58
+ _log.error("PIL not available!")
59
+ return None, None
60
+
61
+ # Priority: Noto > DejaVu > Liberation
62
+ reg_paths = [
63
+ "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
64
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
65
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
66
+ "/usr/share/fonts/truetype/freefont/FreeSans.ttf",
67
+ ]
68
+ bold_paths = [
69
+ "/usr/share/fonts/truetype/noto/NotoSans-Bold.ttf",
70
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
71
+ "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
72
+ "/usr/share/fonts/truetype/freefont/FreeSans.ttf",
73
+ ]
74
+
75
+ for path in reg_paths:
76
+ if os.path.exists(path):
77
+ try:
78
+ _VN_FONT_REG = ImageFont.truetype(path, 40)
79
+ _log.info(f"Found regular font: {path}")
80
+ break
81
+ except:
82
+ continue
83
+
84
+ for path in bold_paths:
85
+ if os.path.exists(path):
86
+ try:
87
+ _VN_FONT_BOLD = ImageFont.truetype(path, 52)
88
+ _log.info(f"Found bold font: {path}")
89
+ break
90
+ except:
91
+ continue
92
+
93
+ if _VN_FONT_REG is None:
94
+ _VN_FONT_REG = ImageFont.load_default()
95
+ if _VN_FONT_BOLD is None:
96
+ _VN_FONT_BOLD = _VN_FONT_REG
97
+
98
+ return _VN_FONT_REG, _VN_FONT_BOLD
99
+
100
+
101
+ def _clean(s):
102
+ import html as html_lib
103
+ return re.sub(r"\s+", " ", html_lib.unescape(str(s or ""))).strip()
104
+
105
+
106
+ # ===== ROBUST TEXT SEGMENTATION =====
107
+ def _split_into_segments(text, max_segments=10, min_len=30):
108
+ """Split text into segments - multi strategy."""
109
+ text = _clean(text)
110
+ if not text:
111
+ return []
112
+
113
+ # Strategy 1: bullet points
114
+ lines = text.split('\n')
115
+ segmented = []
116
+ for line in lines:
117
+ line = _clean(line)
118
+ line_bare = re.sub(r'^[•\-\*\d\.\)\s]+', '', line).strip()
119
+ if len(line_bare) > min_len:
120
+ segmented.append(line_bare)
121
+ elif len(line) > min_len:
122
+ segmented.append(line)
123
+
124
+ # Strategy 2: sentences (Vietnamese)
125
+ if len(segmented) < 2:
126
+ sents = re.split(r'(?<=[.!?])\s+(?=[A-Z0-9À-ỸĐ])', text)
127
+ segmented = [s for s in sents if len(_clean(s)) > min_len]
128
+
129
+ # Strategy 3: character chunks
130
+ if not segmented:
131
+ words = text.split()
132
+ for i in range(0, min(len(words), max_segments * 20), 20):
133
+ chunk = ' '.join(words[i:i+20])
134
+ if len(chunk) > min_len:
135
+ segmented.append(chunk)
136
+
137
+ # Strategy 4: fallback
138
+ if not segmented:
139
+ segmented = [text[:300]]
140
+
141
+ return segmented[:max_segments]
142
+
143
+
144
+ # ===== SHORT VIDEO GENERATOR =====
145
+ def _gen_short_core(post, work_dir):
146
+ """Core short generation - returns video path or None."""
147
+ post_id = post.get('id', '')
148
+ text = post.get('text', '') or post.get('title', '')
149
+
150
+ if not post_id or len(text) < 100:
151
+ _log.error(f"Invalid post: id={post_id}, text_len={len(text)}")
152
+ return None
153
+
154
+ segments = _split_into_segments(text, max_segments=10, min_len=30)
155
+ if not segments:
156
+ _log.error("No segments generated")
157
+ return None
158
+
159
+ _log.info(f"Generating short: {len(segments)} segments")
160
+
161
+ seg_hash = hashlib.md5(('|'.join(segments) + 'nu').encode()).hexdigest()[:8]
162
+ suffix = f"_nu_{seg_hash}"
163
+ out_mp4 = os.path.join(work_dir, f"{post_id}{suffix}.mp4")
164
+
165
+ if os.path.exists(out_mp4):
166
+ _log.info(f"Already exists: {out_mp4}")
167
+ return out_mp4
168
+
169
+ # Check dependencies
170
+ try:
171
+ subprocess.run(['ffmpeg', '-version'], capture_output=True, timeout=5)
172
+ except Exception as e:
173
+ _log.error(f"ffmpeg missing: {e}")
174
+ return None
175
+
176
+ # Download image
177
+ img_path = os.path.join(work_dir, 'bg.jpg')
178
+ downloaded = False
179
+ try:
180
+ img_url = post.get('img', '')
181
+ if img_url and img_url.startswith('http'):
182
+ r = requests.get(img_url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=12)
183
+ if r.status_code == 200:
184
+ with open(img_path, 'wb') as f:
185
+ f.write(r.content)
186
+ downloaded = True
187
+ except Exception as e:
188
+ _log.warning(f"Image download: {e}")
189
+
190
+ try:
191
+ from PIL import Image, ImageDraw
192
+ has_pil = True
193
+ except:
194
+ has_pil = False
195
+ _log.warning("PIL not available")
196
+
197
+ try:
198
+ from gtts import gTTS
199
+ has_tts = True
200
+ except:
201
+ has_tts = False
202
+ _log.warning("gTTS not available")
203
+
204
+ parts = []
205
+
206
+ for i, seg in enumerate(segments[:10]):
207
+ frame = os.path.join(work_dir, f'frame_{i}.jpg')
208
+ audio = os.path.join(work_dir, f'audio_{i}.mp3')
209
+ part = os.path.join(work_dir, f'part_{i}.mp4')
210
+
211
+ # Create frame
212
+ try:
213
+ if has_pil:
214
+ _make_frame(post, seg, img_path, downloaded, frame)
215
+ else:
216
+ subprocess.run(['ffmpeg', '-y', '-f', 'lavfi', '-i',
217
+ 'color=c=black:s=1080x1920:d=1', '-frames:v', '1', frame],
218
+ capture_output=True, timeout=20)
219
+ except Exception as e:
220
+ _log.error(f"Frame error: {e}")
221
+ continue
222
+
223
+ # Create audio
224
+ if has_tts:
225
+ try:
226
+ tts = _clean(seg)[:300]
227
+ gTTS(tts, lang='vi', slow=False).save(audio)
228
+ except Exception as e:
229
+ _log.warning(f"TTS error: {e}")
230
+ audio = None
231
+
232
+ # Combine
233
+ dur = 10
234
+ try:
235
+ cmd = ['ffmpeg', '-y', '-loop', '1', '-t', str(dur), '-i', frame]
236
+ if has_tts and os.path.exists(audio):
237
+ cmd += ['-i', audio, '-shortest']
238
+ else:
239
+ cmd += ['-f', 'lavfi', '-i', 'anullsrc', '-shortest']
240
+ cmd += ['-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p',
241
+ '-c:a', 'aac', '-b:a', '128k', part]
242
+ subprocess.run(cmd, capture_output=True, timeout=120)
243
+ if os.path.exists(part) and os.path.getsize(part) > 5000:
244
+ parts.append(part)
245
+ except Exception as e:
246
+ _log.error(f"Part combine error: {e}")
247
+
248
+ if not parts:
249
+ _log.error("No video parts created!")
250
+ return None
251
+
252
+ # Concatenate
253
+ try:
254
+ concat = os.path.join(work_dir, 'list.txt')
255
+ with open(concat, 'w') as f:
256
+ for p in parts:
257
+ f.write(f"file '{p}'\n")
258
+ subprocess.run(['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat, '-c', 'copy', out_mp4],
259
+ capture_output=True, timeout=180)
260
+ _log.info(f"Short created: {out_mp4}")
261
+ return out_mp4
262
+ except Exception as e:
263
+ _log.error(f"Concat error: {e}")
264
+ return None
265
+
266
+
267
+ def _make_frame(post, text, img_path, downloaded, out_path):
268
+ """Create video frame with Vietnamese font."""
269
+ from PIL import Image, ImageDraw
270
+ _get_vn_fonts()
271
+
272
+ W, H = 1080, 1920
273
+ bg = Image.new('RGB', (W, H), (15, 23, 38))
274
+ d = ImageDraw.Draw(bg)
275
+
276
+ # Background image
277
+ if downloaded and os.path.exists(img_path):
278
+ try:
279
+ im = Image.open(img_path).convert('RGB')
280
+ im = im.resize((W, 760))
281
+ bg.paste(im, (0, 0))
282
+ except:
283
+ pass
284
+
285
+ # Title
286
+ d.rectangle([0, 0, W, 100], fill=(25, 118, 210))
287
+ ttl = post.get('title', '')[:50]
288
+ if _VN_FONT_BOLD:
289
+ d.text((W//2, 50), ttl, fill='white', font=_VN_FONT_BOLD, anchor='mm')
290
+
291
+ # Content
292
+ y = 150
293
+ for ln in _wrap_text(d, text[:200], _VN_FONT_REG, 80, 920, 10):
294
+ d.text((80, y), ln, fill='white', font=_VN_FONT_REG)
295
+ y += 55
296
+
297
+ bg.save(out_path, quality=85)
298
+
299
+
300
+ def _wrap_text(draw, text, font, x, max_w, max_lines):
301
+ """Word wrap text."""
302
+ words = text.split()
303
+ lines = []
304
+ cur = []
305
+ for w in words:
306
+ test = ' '.join(cur + [w])
307
+ try:
308
+ w_px = draw.textbbox((0, 0), test, font=font)[2]
309
+ except:
310
+ w_px = len(test) * 22
311
+ if w_px <= max_w:
312
+ cur.append(w)
313
+ else:
314
+ if cur:
315
+ lines.append(' '.join(cur))
316
+ cur = [w]
317
+ if len(lines) >= max_lines:
318
+ break
319
+ if cur and len(lines) < max_lines:
320
+ lines.append(' '.join(cur))
321
+ return lines
322
+
323
+
324
+ def _gen_short_sync(post) -> str:
325
+ """Sync wrapper - returns video URL."""
326
+ work = os.path.join(SHORTS_DIR, f"work_{post.get('id', int(time.time()))}")
327
+ os.makedirs(work, exist_ok=True)
328
+ result = _gen_short_core(post, work)
329
+ if result:
330
+ # Update wall
331
+ try:
332
+ wall = base._load_ai_wall()
333
+ for i, p in enumerate(wall):
334
+ if str(p.get('id')) == str(post.get('id')):
335
+ p['video'] = f'/api/ai/short-file/{post.get("id")}_nu_{hashlib.md5(str(post).encode()).hexdigest()[:8]}'
336
+ wall[i] = p
337
+ break
338
+ base._save_ai_wall(wall)
339
+ except Exception as e:
340
+ _log.warning(f"Wall update: {e}")
341
+ return result
342
+ return ''
343
+
344
+
345
+ # ===== REGISTER ENDPOINTS - MUST BE AT MODULE LEVEL =====
346
+ @app.post('/api/ai/short/{post_id}')
347
+ async def api_short_generate(post_id: str, request: Request):
348
+ _log.info(f"POST /api/ai/short/{post_id}")
349
+ wall = base._load_ai_wall()
350
+ post = next((p for p in wall if str(p.get('id')) == str(post_id)), None)
351
+ if not post:
352
+ return JSONResponse({'error': 'Post not found in wall'}, status_code=404)
353
+
354
+ if post.get('video'):
355
+ return JSONResponse({'post': post, 'video': post['video'], 'status': 'done'})
356
+
357
+ loop = asyncio.get_event_loop()
358
+ result = await loop.run_in_executor(None, _gen_short_sync, post)
359
+
360
+ if result:
361
+ # Get the video URL from wall (updated in _gen_short_sync)
362
+ wall = base._load_ai_wall()
363
+ post = next((p for p in wall if str(p.get('id')) == str(post_id)), post)
364
+ return JSONResponse({'post': post, 'video': post.get('video'), 'status': 'done'})
365
+ return JSONResponse({'error': 'Video generation failed'}, status_code=500)
366
+
367
+
368
+ @app.get('/api/ai/short-file/{file_id:path}')
369
+ async def api_short_file(file_id: str):
370
+ safe = re.sub(r'[^\w\-.]', '_', file_id)[:100]
371
+ for fname in os.listdir(SHORTS_DIR) if os.path.isdir(SHORTS_DIR) else []:
372
+ if fname.endswith('.mp4') and safe in fname:
373
+ return FileResponse(os.path.join(SHORTS_DIR, fname), media_type='video/mp4')
374
+ return JSONResponse({'error': 'Not found'}, status_code=404)
375
+
376
+
377
+ # Log startup
378
+ _log.info("Short video endpoints registered")