import os import random from fastapi import FastAPI, Query from fastapi.middleware.cors import CORSMiddleware import google.generativeai as genai from googleapiclient.discovery import build app = FastAPI() # Blogger domain ko allow karne ke liye (CORS) app.add_middleware( CORSMiddleware, allow_origins=["*"], # Yahan baad mein apna domain dal sakte hain allow_methods=["*"], allow_headers=["*"], ) # --- CONFIGURATION (Keys Rotation Logic) --- # Hugging Face Settings -> Secrets mein ye naam save karein: # GEMINI_KEYS aur YOUTUBE_KEYS (Comma separated keys dalein) GEMINI_KEYS = os.getenv("GEMINI_KEYS", "").split(",") YOUTUBE_KEYS = os.getenv("YOUTUBE_KEYS", "").split(",") def get_gemini_model(): key = random.choice(GEMINI_KEYS).strip() genai.configure(api_key=key) return genai.GenerativeModel('gemini-1.5-flash') def get_youtube_service(): key = random.choice(YOUTUBE_KEYS).strip() return build('youtube', 'v3', developerKey=key) # --- CORE LOGIC --- @app.get("/generate") async def generate_strategy(keyword: str): try: # 1. Get YouTube Data (Top Video Titles & Tags) youtube = get_youtube_service() search_response = youtube.search().list( q=keyword, part='snippet', maxResults=5, type='video' ).execute() video_data = "" for item in search_response['items']: video_data += f"Title: {item['snippet']['title']}\n" # 2. Ask Gemini to analyze and create strategy model = get_gemini_model() prompt = f""" Analyze the following YouTube top results for the keyword: "{keyword}" Data: {video_data} Please provide: 1. 10 High-ranking Tags (comma separated). 2. 4 Viral Clickbait Titles. 3. A short 3-sentence SEO strategy for this video. Format the output strictly like this: TAGS: [tags here] TITLES: [title 1], [title 2], [title 3], [title 4] STRATEGY: [strategy text here] """ response = model.generate_content(prompt) content = response.text # 3. Parse the output # Simple parsing logic tags = content.split("TAGS:")[1].split("TITLES:")[0].strip() titles = content.split("TITLES:")[1].split("STRATEGY:")[0].strip().split(",") strategy = content.split("STRATEGY:")[1].strip() return { "success": True, "tags": tags.split(","), "titles": titles, "strategy": strategy } except Exception as e: return {"success": False, "error": str(e)} @app.get("/") def home(): return {"status": "TubeRocket API is Running!"}