Download src/gemini_generator.py from ayush77uh/yt: direct link, hf CLI and curl.
- Browser
- Download file 7.86 kB
-
https://huggingface.co/spaces/ayush77uh/yt/resolve/main/src/gemini_generator.py
- Command line
-
hf download hf://spaces/ayush77uh/yt/src/gemini_generator.py
-
curl -L -o gemini_generator.py https://huggingface.co/spaces/ayush77uh/yt/resolve/main/src/gemini_generator.py
7.86 kB
| import os | |
| import random | |
| from google import genai | |
| from google.genai import types | |
| class GeminiScriptGenerator: | |
| def __init__(self): | |
| # API Key from Environment | |
| self.api_key = os.environ.get("GEMINI_API_KEY") | |
| if not self.api_key: | |
| print("❌ GEMINI_API_KEY not found in environment variables.", flush=True) | |
| self.client = None | |
| return | |
| try: | |
| self.client = genai.Client(api_key=self.api_key) | |
| print("✅ Gemini Client Initialized (google-genai SDK)", flush=True) | |
| except Exception as e: | |
| print(f"❌ Failed to initialize Gemini Client: {e}", flush=True) | |
| self.client = None | |
| def generate_script(self): | |
| if not self.client: | |
| return None, "Error_No_Gemini_Client" | |
| # Topic Rotation | |
| topics = [ | |
| "Dark Psychology: How People Control You Without Force", | |
| "The Psychology of Manipulation in Daily Life", | |
| "How Gaslighting Makes You Doubt Yourself", | |
| "Why Silent Treatment Is Psychological Control", | |
| "How Narcissists Use Praise and Punishment", | |
| "The Dark Psychology of Guilt Tripping", | |
| "How People Use Fear of Loss Against You", | |
| "The Psychology of Love Bombing", | |
| "How Toxic People Test Your Boundaries", | |
| "The Psychology of Emotional Blackmail", | |
| "Why Some People Always Play the Victim", | |
| "How Triangulation Creates Jealousy and Control", | |
| "The Psychology of Push-Pull Behavior", | |
| "How People Use Confusion to Control You", | |
| "Why Over-Explaining Makes You Easier to Control", | |
| "The Dark Psychology of Intermittent Reward", | |
| "How Fake Nice People Manipulate Trust", | |
| "The Psychology of Power in Relationships", | |
| "How Manipulators Make You Feel Responsible for Their Emotions", | |
| "Why Walking Away Breaks Manipulation", | |
| "Why Your 20s Decide Your Whole Life", | |
| "How to Build Discipline Without Motivation", | |
| "Why Most Students Waste Time Without Realizing It", | |
| "Dark Psychology Tricks People Use in Daily Life", | |
| "How to Read People's Intentions Through Small Behaviors", | |
| "Why Confidence Makes People Treat You Differently", | |
| "The Psychology of Focus in a Distracted World", | |
| "Why Some People Become Addicted to Comfort", | |
| "How to Stop Overthinking and Take Control", | |
| "The Hidden Psychology of Respect and Status", | |
| "Why Consistency Beats Talent Every Time", | |
| "How to Train Your Mind for Success" | |
| ] | |
| topic = random.choice(topics) | |
| print(f"🧠 Gemini Generating Script on Topic: {topic}...", flush=True) | |
| system_prompt = ( | |
| "You are an expert YouTube script writer for an English self-improvement and psychology channel. " | |
| "Your writing feels intense, cinematic, smart, addictive, calm, sharp, and psychologically observant. " | |
| "You write like a smart creator talking directly to viewers, not like a teacher reading notes." | |
| ) | |
| user_prompt = ( | |
| f"TOPIC: {topic}\n\n" | |
| "Write a HIGH RETENTION YouTube script in natural English only.\n" | |
| "Requirements:\n" | |
| "1. VIDEO LENGTH TARGET: 8 minutes.\n" | |
| "2. Strong hook in the first 15 seconds. Do NOT say hello, welcome, or intro lines.\n" | |
| "3. Build curiosity fast using tension, questions, twists, and sharp observations.\n" | |
| "4. Explain ideas using realistic real-life examples: students, career, relationships, discipline, social behavior, phone addiction, comfort zone, status, confidence.\n" | |
| "5. Every 20-30 seconds must contain a hook, question, twist, or insight.\n" | |
| "6. Tone: calm, sharp, psychologically intense. Avoid cringe motivation lines and robotic explanations.\n" | |
| "7. Use short punchy lines. Keep pacing tight. No filler. Do NOT repeat points.\n" | |
| "8. Occasionally use dramatic pauses naturally, like: 'And this is where the game begins...', 'Most people never notice this...', 'That is not a coincidence.'\n" | |
| "9. End with a strong conclusion or uncomfortable question that makes the viewer think.\n" | |
| "10. After the spoken script, add title suggestions and thumbnail text ideas only.\n" | |
| "11. Do not add SEO keywords inside the script or after the script.\n" | |
| "12. Format clearly with these labels only: SCRIPT:, TITLE SUGGESTIONS:, THUMBNAIL TEXT IDEAS:.\n" | |
| "12. The SCRIPT section must be clean for TTS reading and should be around 1100-1300 words." | |
| ) | |
| # List of models to try in order (Fastest -> Fallback) | |
| # These IDs are from ListModels output for this API key | |
| models_to_try = [ | |
| "gemini-2.5-flash-preview-09-2025", # Latest 2.5 Flash | |
| "gemini-flash-latest", # Stable Flash alias | |
| "gemini-pro-latest", # Pro alias | |
| ] | |
| for model_id in models_to_try: | |
| try: | |
| print(f"🧠 Trying Gemini Model: {model_id}...", flush=True) | |
| # Flash Config (No Thinking Mode to save tokens/time) | |
| generate_content_config = types.GenerateContentConfig( | |
| temperature=1.0, # High Creativity | |
| max_output_tokens=4096, | |
| safety_settings=[ | |
| types.SafetySetting(category="HARM_CATEGORY_HARASSMENT", threshold="BLOCK_NONE"), | |
| types.SafetySetting(category="HARM_CATEGORY_HATE_SPEECH", threshold="BLOCK_NONE"), | |
| types.SafetySetting(category="HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold="BLOCK_NONE"), | |
| types.SafetySetting(category="HARM_CATEGORY_DANGEROUS_CONTENT", threshold="BLOCK_NONE"), | |
| types.SafetySetting(category="HARM_CATEGORY_CIVIC_INTEGRITY", threshold="BLOCK_NONE"), | |
| ], | |
| ) | |
| contents = [ | |
| types.Content( | |
| role="user", | |
| parts=[ | |
| types.Part.from_text(text=f"{system_prompt}\n\n{user_prompt}"), | |
| ], | |
| ), | |
| ] | |
| # Collect full response | |
| full_text = "" | |
| for chunk in self.client.models.generate_content_stream( | |
| model=model_id, | |
| contents=contents, | |
| config=generate_content_config, | |
| ): | |
| if chunk.text: | |
| full_text += chunk.text | |
| print(f"\n✅ Gemini Generation Complete ({model_id})!", flush=True) | |
| script_content = full_text.strip() | |
| # Validation | |
| if len(script_content) < 500: | |
| print(f"⚠️ Generated script too short ({len(script_content)} chars)!", flush=True) | |
| continue # Try next model | |
| # Log Full Script | |
| print(f"\n📜 FULL GEMINI SCRIPT ({len(script_content)} chars):\n" + "="*50 + f"\n{script_content}\n" + "="*50 + "\n", flush=True) | |
| return script_content, topic | |
| except Exception as e: | |
| print(f"⚠️ Model {model_id} failed: {e}", flush=True) | |
| continue # Try next model | |
| return None, "All_Gemini_Models_Failed" | |
| if __name__ == "__main__": | |
| # Test | |
| gen = GeminiScriptGenerator() | |
| script, topic = gen.generate_script() | |
| print(f"Topic: {topic}") | |