yukee1992 commited on
Commit
bdac9c8
Β·
verified Β·
1 Parent(s): 361b72d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -84
app.py CHANGED
@@ -21,8 +21,6 @@ API_KEY = os.getenv("API_KEY", "default-key-123")
21
  MAX_TOKENS = 450
22
  DEVICE = "cpu"
23
  PORT = int(os.getenv("PORT", 7860))
24
- TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
25
- TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "")
26
 
27
  # Setup logging
28
  logging.basicConfig(
@@ -88,34 +86,6 @@ async def lifespan(app: FastAPI):
88
 
89
  app = FastAPI(lifespan=lifespan)
90
 
91
- async def send_telegram_message(message: str):
92
- """Send message to Telegram"""
93
- if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
94
- logger.warning("Telegram credentials not configured")
95
- return False
96
-
97
- try:
98
- url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
99
- payload = {
100
- "chat_id": TELEGRAM_CHAT_ID,
101
- "text": message,
102
- "parse_mode": "HTML",
103
- "disable_web_page_preview": True
104
- }
105
-
106
- async with httpx.AsyncClient(timeout=10.0) as client:
107
- response = await client.post(url, json=payload)
108
- if response.status_code == 200:
109
- logger.info("πŸ“¨ Telegram notification sent")
110
- return True
111
- else:
112
- logger.error(f"❌ Telegram API error: {response.status_code} - {response.text}")
113
- return False
114
-
115
- except Exception as e:
116
- logger.error(f"❌ Telegram notification failed: {str(e)}")
117
- return False
118
-
119
  def extract_topics(topic_input: Union[str, List[str]]) -> List[str]:
120
  """Extract and validate topics from input"""
121
  if isinstance(topic_input, str):
@@ -244,7 +214,7 @@ def generate_script(topic: str) -> str:
244
  "- Use conversational, engaging tone\n"
245
  "- End with strong, clear call-to-action\n\n"
246
 
247
- "EXAMPLE FORMAT:\n"
248
  "[0:00-0:08] VISUAL: dramatic time-lapse of vibrant superfoods being prepared\n"
249
  "VOICEOVER: This one simple change can boost your energy by 200% in just 30 days\n\n"
250
 
@@ -304,10 +274,6 @@ async def process_job(job_id: str, topics_input: Union[str, List[str]], callback
304
 
305
  logger.info(f"🎯 Processing {len(topics)} topics: {topics}")
306
 
307
- # Send start notification to Telegram
308
- start_message = f"πŸš€ <b>Script Generation Started</b>\n\nTopics: {', '.join(topics[:3])}{'...' if len(topics) > 3 else ''}"
309
- asyncio.create_task(send_telegram_message(start_message))
310
-
311
  # Step 1: Generate a viral topic from the trends
312
  generated_topic = generate_topic_from_trends(topics)
313
 
@@ -326,19 +292,6 @@ async def process_job(job_id: str, topics_input: Union[str, List[str]], callback
326
 
327
  logger.info(f"βœ… Completed job {job_id}")
328
 
329
- # Send completion notification to Telegram
330
- completion_message = f"""
331
- βœ… <b>Script Generation Complete!</b>
332
-
333
- 🏷️ <b>Generated Topic:</b> {generated_topic}
334
-
335
- πŸ“ <b>Script Length:</b> {len(script)} characters
336
- πŸ•’ <b>Estimated Video Duration:</b> 60 seconds
337
-
338
- πŸ”— <b>View in n8n:</b> Check your workflow for the complete script
339
- """
340
- asyncio.create_task(send_telegram_message(completion_message))
341
-
342
  # Send webhook callback if URL provided
343
  if callback_url:
344
  try:
@@ -359,7 +312,10 @@ async def process_job(job_id: str, topics_input: Union[str, List[str]], callback
359
  headers={"Content-Type": "application/json"}
360
  )
361
 
362
- logger.info(f"πŸ“¨ Webhook status: {response.status_code}")
 
 
 
363
 
364
  except Exception as e:
365
  logger.error(f"❌ Webhook failed: {str(e)}")
@@ -368,10 +324,6 @@ async def process_job(job_id: str, topics_input: Union[str, List[str]], callback
368
  error_msg = f"Job failed: {str(e)}"
369
  logger.error(f"❌ Job {job_id} failed: {error_msg}")
370
 
371
- # Send error notification to Telegram
372
- error_message = f"❌ <b>Script Generation Failed</b>\n\nError: {str(e)}"
373
- asyncio.create_task(send_telegram_message(error_message))
374
-
375
  # Store failure information
376
  jobs[job_id] = {
377
  "status": "failed",
@@ -390,10 +342,11 @@ async def process_job(job_id: str, topics_input: Union[str, List[str]], callback
390
  "status": "failed",
391
  "error": error_msg,
392
  "topics": extract_topics(topics_input) if topics_input else []
393
- }
 
394
  )
395
- except Exception:
396
- logger.error("Failed to send error webhook")
397
 
398
  @app.post("/api/submit")
399
  async def submit_job(
@@ -451,7 +404,8 @@ async def get_status(job_id: str, auth: bool = Depends(verify_api_key)):
451
  """Check job status"""
452
  if job_id not in jobs:
453
  raise HTTPException(status_code=404, detail="Job not found")
454
- return jobs[job_id]
 
455
 
456
  @app.get("/health")
457
  async def health_check():
@@ -459,14 +413,14 @@ async def health_check():
459
  completed_jobs = [job for job in jobs.values() if job.get("status") == "complete"]
460
  avg_length = sum(job.get("script_length", 0) for job in completed_jobs) / max(1, len(completed_jobs))
461
 
462
- return {
463
  "status": "healthy",
464
  "model_loaded": generator.loaded,
465
  "total_jobs": len(jobs),
466
  "completed_jobs": len(completed_jobs),
467
  "failed_jobs": sum(1 for job in jobs.values() if job.get("status") == "failed"),
468
  "average_script_length": round(avg_length, 2)
469
- }
470
 
471
  @app.get("/test/generation")
472
  async def test_generation(auth: bool = Depends(verify_api_key)):
@@ -474,7 +428,7 @@ async def test_generation(auth: bool = Depends(verify_api_key)):
474
  try:
475
  if not generator.loaded:
476
  if not generator.load_model():
477
- return {"status": "error", "error": "Model failed to load"}
478
 
479
  test_topics = [
480
  "Artificial Intelligence",
@@ -492,7 +446,7 @@ async def test_generation(auth: bool = Depends(verify_api_key)):
492
  # Test script generation
493
  script = generate_script(generated_topic)
494
 
495
- return {
496
  "status": "success",
497
  "test_topics": test_topics,
498
  "generated_topic": generated_topic,
@@ -500,39 +454,27 @@ async def test_generation(auth: bool = Depends(verify_api_key)):
500
  "script_preview": script[:300] + "..." if len(script) > 300 else script,
501
  "estimated_duration": "60 seconds",
502
  "quality": "good" if len(script) >= 800 else "needs improvement"
503
- }
504
 
505
  except Exception as e:
506
  logger.error(f"❌ Test generation failed: {str(e)}")
507
- return {"status": "error", "error": str(e)}
508
-
509
- @app.get("/test/telegram")
510
- async def test_telegram(auth: bool = Depends(verify_api_key)):
511
- """Test Telegram notification"""
512
- test_message = "πŸ”” <b>Test Notification</b>\n\nThis is a test message from your Script Generator API"
513
- success = await send_telegram_message(test_message)
514
-
515
- return {
516
- "status": "success" if success else "error",
517
- "message": "Telegram test sent" if success else "Telegram test failed",
518
- "bot_configured": bool(TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID)
519
- }
520
 
521
  @app.get("/")
522
  async def root():
523
  """Root endpoint"""
524
- return {
525
- "message": "Enhanced Video Script Generator API with Telegram Notifications",
526
- "version": "2.1",
527
- "features": "Generates viral topics from trends, creates scripts, and sends Telegram notifications",
528
  "endpoints": {
529
  "submit_job": "POST /api/submit (with 'topics' array)",
530
  "check_status": "GET /api/status/{job_id}",
531
  "health": "GET /health",
532
- "test_generation": "GET /test/generation",
533
- "test_telegram": "GET /test/telegram"
534
  },
535
- }
 
536
 
537
  if __name__ == "__main__":
538
  uvicorn.run(
@@ -540,5 +482,4 @@ if __name__ == "__main__":
540
  host="0.0.0.0",
541
  port=PORT,
542
  log_level="info"
543
- )
544
-
 
21
  MAX_TOKENS = 450
22
  DEVICE = "cpu"
23
  PORT = int(os.getenv("PORT", 7860))
 
 
24
 
25
  # Setup logging
26
  logging.basicConfig(
 
86
 
87
  app = FastAPI(lifespan=lifespan)
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  def extract_topics(topic_input: Union[str, List[str]]) -> List[str]:
90
  """Extract and validate topics from input"""
91
  if isinstance(topic_input, str):
 
214
  "- Use conversational, engaging tone\n"
215
  "- End with strong, clear call-to-action\n\n"
216
 
217
+ "EXAMPLE FORFORMAT:\n"
218
  "[0:00-0:08] VISUAL: dramatic time-lapse of vibrant superfoods being prepared\n"
219
  "VOICEOVER: This one simple change can boost your energy by 200% in just 30 days\n\n"
220
 
 
274
 
275
  logger.info(f"🎯 Processing {len(topics)} topics: {topics}")
276
 
 
 
 
 
277
  # Step 1: Generate a viral topic from the trends
278
  generated_topic = generate_topic_from_trends(topics)
279
 
 
292
 
293
  logger.info(f"βœ… Completed job {job_id}")
294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  # Send webhook callback if URL provided
296
  if callback_url:
297
  try:
 
312
  headers={"Content-Type": "application/json"}
313
  )
314
 
315
+ if response.status_code >= 200 and response.status_code < 300:
316
+ logger.info(f"πŸ“¨ Webhook delivered successfully: {response.status_code}")
317
+ else:
318
+ logger.warning(f"⚠️ Webhook returned non-2xx status: {response.status_code}")
319
 
320
  except Exception as e:
321
  logger.error(f"❌ Webhook failed: {str(e)}")
 
324
  error_msg = f"Job failed: {str(e)}"
325
  logger.error(f"❌ Job {job_id} failed: {error_msg}")
326
 
 
 
 
 
327
  # Store failure information
328
  jobs[job_id] = {
329
  "status": "failed",
 
342
  "status": "failed",
343
  "error": error_msg,
344
  "topics": extract_topics(topics_input) if topics_input else []
345
+ },
346
+ headers={"Content-Type": "application/json"}
347
  )
348
+ except Exception as e:
349
+ logger.error(f"Failed to send error webhook: {e}")
350
 
351
  @app.post("/api/submit")
352
  async def submit_job(
 
404
  """Check job status"""
405
  if job_id not in jobs:
406
  raise HTTPException(status_code=404, detail="Job not found")
407
+
408
+ return JSONResponse(jobs[job_id])
409
 
410
  @app.get("/health")
411
  async def health_check():
 
413
  completed_jobs = [job for job in jobs.values() if job.get("status") == "complete"]
414
  avg_length = sum(job.get("script_length", 0) for job in completed_jobs) / max(1, len(completed_jobs))
415
 
416
+ return JSONResponse({
417
  "status": "healthy",
418
  "model_loaded": generator.loaded,
419
  "total_jobs": len(jobs),
420
  "completed_jobs": len(completed_jobs),
421
  "failed_jobs": sum(1 for job in jobs.values() if job.get("status") == "failed"),
422
  "average_script_length": round(avg_length, 2)
423
+ })
424
 
425
  @app.get("/test/generation")
426
  async def test_generation(auth: bool = Depends(verify_api_key)):
 
428
  try:
429
  if not generator.loaded:
430
  if not generator.load_model():
431
+ return JSONResponse({"status": "error", "error": "Model failed to load"})
432
 
433
  test_topics = [
434
  "Artificial Intelligence",
 
446
  # Test script generation
447
  script = generate_script(generated_topic)
448
 
449
+ return JSONResponse({
450
  "status": "success",
451
  "test_topics": test_topics,
452
  "generated_topic": generated_topic,
 
454
  "script_preview": script[:300] + "..." if len(script) > 300 else script,
455
  "estimated_duration": "60 seconds",
456
  "quality": "good" if len(script) >= 800 else "needs improvement"
457
+ })
458
 
459
  except Exception as e:
460
  logger.error(f"❌ Test generation failed: {str(e)}")
461
+ return JSONResponse({"status": "error", "error": str(e)})
 
 
 
 
 
 
 
 
 
 
 
 
462
 
463
  @app.get("/")
464
  async def root():
465
  """Root endpoint"""
466
+ return JSONResponse({
467
+ "message": "Video Script Generator API",
468
+ "version": "2.0",
469
+ "features": "Generates viral topics from trends and creates video scripts",
470
  "endpoints": {
471
  "submit_job": "POST /api/submit (with 'topics' array)",
472
  "check_status": "GET /api/status/{job_id}",
473
  "health": "GET /health",
474
+ "test_generation": "GET /test/generation"
 
475
  },
476
+ "status": "operational"
477
+ })
478
 
479
  if __name__ == "__main__":
480
  uvicorn.run(
 
482
  host="0.0.0.0",
483
  port=PORT,
484
  log_level="info"
485
+ )