yukee1992 commited on
Commit
55661d2
Β·
verified Β·
1 Parent(s): 8276501

Telegram included

Browse files
Files changed (1) hide show
  1. app.py +70 -15
app.py CHANGED
@@ -5,6 +5,7 @@ import torch
5
  import logging
6
  import re
7
  import json
 
8
  from typing import Dict, Optional, List, Union
9
  from fastapi import FastAPI, Request, BackgroundTasks, HTTPException, Depends
10
  from fastapi.responses import JSONResponse
@@ -20,6 +21,8 @@ API_KEY = os.getenv("API_KEY", "default-key-123")
20
  MAX_TOKENS = 450
21
  DEVICE = "cpu"
22
  PORT = int(os.getenv("PORT", 7860))
 
 
23
 
24
  # Setup logging
25
  logging.basicConfig(
@@ -85,6 +88,34 @@ async def lifespan(app: FastAPI):
85
 
86
  app = FastAPI(lifespan=lifespan)
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  def extract_topics(topic_input: Union[str, List[str]]) -> List[str]:
89
  """Extract and validate topics from input"""
90
  if isinstance(topic_input, str):
@@ -273,6 +304,10 @@ async def process_job(job_id: str, topics_input: Union[str, List[str]], callback
273
 
274
  logger.info(f"🎯 Processing {len(topics)} topics: {topics}")
275
 
 
 
 
 
276
  # Step 1: Generate a viral topic from the trends
277
  generated_topic = generate_topic_from_trends(topics)
278
 
@@ -291,6 +326,19 @@ async def process_job(job_id: str, topics_input: Union[str, List[str]], callback
291
 
292
  logger.info(f"βœ… Completed job {job_id}")
293
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
  # Send webhook callback if URL provided
295
  if callback_url:
296
  try:
@@ -320,6 +368,10 @@ async def process_job(job_id: str, topics_input: Union[str, List[str]], callback
320
  error_msg = f"Job failed: {str(e)}"
321
  logger.error(f"❌ Job {job_id} failed: {error_msg}")
322
 
 
 
 
 
323
  # Store failure information
324
  jobs[job_id] = {
325
  "status": "failed",
@@ -454,26 +506,29 @@ async def test_generation(auth: bool = Depends(verify_api_key)):
454
  logger.error(f"❌ Test generation failed: {str(e)}")
455
  return {"status": "error", "error": str(e)}
456
 
 
 
 
 
 
 
 
 
 
 
 
 
457
  @app.get("/")
458
  async def root():
459
  """Root endpoint"""
460
  return {
461
- "message": "Enhanced Video Script Generator API",
462
- "version": "2.0",
463
- "features": "Generates viral topics from trends, then creates scripts",
464
  "endpoints": {
465
  "submit_job": "POST /api/submit (with 'topics' array)",
466
  "check_status": "GET /api/status/{job_id}",
467
  "health": "GET /health",
468
- "test": "GET /test/generation"
469
- },
470
- "status": "operational"
471
- }
472
-
473
- if __name__ == "__main__":
474
- uvicorn.run(
475
- app,
476
- host="0.0.0.0",
477
- port=PORT,
478
- log_level="info"
479
- )
 
5
  import logging
6
  import re
7
  import json
8
+ import asyncio
9
  from typing import Dict, Optional, List, Union
10
  from fastapi import FastAPI, Request, BackgroundTasks, HTTPException, Depends
11
  from fastapi.responses import JSONResponse
 
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
 
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):
 
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
 
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:
 
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",
 
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
+ },