This SEO plan was generated using AI analysis and industry best practices. Use this as a strategic guide for your content creation process.
import gradio as gr import google.generativeai as genai import os from dotenv import load_dotenv import time import json import markdown # Ensure markdown is imported import base64 from datetime import datetime import re # Load environment variables from .env file if it exists load_dotenv() # Enhanced templates for different food niches DEFAULT_TEMPLATES = { "fermentation": """ Act as an elite-level SEO strategist and content creator with deep expertise in food blogs, particularly fermentation. I run a blog about fermentation, and my primary goal is to increase organic traffic, educate beginners, and establish thought leadership. My target audience is beginners curious about home fermentation and health-conscious individuals. For the specific topic: '{topic}' Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles. I require the following, formatted in clean markdown: 1. **Strategic Keyword Analysis:** * **Primary Target Keyword:** * **Secondary Keywords:** 2-3 closely related, high-intent keywords. * **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases. * **Semantic/LSI Keywords:** 5-7 contextually related terms. * **Search Intent Analysis:** (Informational, Commercial, etc.) 2. **Competitive Landscape Overview (Top 3-5 Competitors):** * For each: * URL * Strengths * Weaknesses * Content angle/hook 3. **Content Gaps & Unique Value Proposition:** * Missing topics or angles * Unique insights or differentiators for *my* blog 4. **Optimized Blog Post Outline:** * **H1 Title:** * **Meta Description:** (under 160 characters) * **Full H2/H3 outline:** * **Suggested Visuals:** Where applicable 5. **User-Focused FAQ Section:** 3–5 related to '{topic}' 6. **Internal & External Linking Plan:** * **Internal:** 2-3 relevant articles with anchor suggestions * **External:** 1-2 reputable sources (.edu, .org, studies) 7. **E-E-A-T Enhancements:** * 1-2 ways to show experience, trust, and authority in the content 8. **SEO Performance Metrics:** * Expected keyword difficulty (1-100) * Estimated monthly search volume * Content length recommendation * Target reading time """, "baking": """ Act as an elite-level SEO strategist and content creator with deep expertise in food blogs, particularly baking and pastry. I run a blog about baking, and my primary goal is to increase organic traffic, help home bakers improve their skills, and showcase unique recipes. My target audience is home bakers of all skill levels looking for reliable recipes and techniques. For the specific topic: '{topic}' Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles. I require the following, formatted in clean markdown: 1. **Strategic Keyword Analysis:** * **Primary Target Keyword:** * **Secondary Keywords:** 2-3 closely related, high-intent keywords. * **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases. * **Seasonal/Holiday Keywords:** 2-3 if applicable * **Search Intent Analysis:** (Recipe-seeking, Technique-learning, Equipment-buying, etc.) 2. **Competitive Landscape Overview (Top 3-5 Competitors):** * For each: * URL * Recipe uniqueness/approach * Visual presentation * User engagement factors 3. **Recipe Uniqueness & Value Proposition:** * Distinctive ingredients or techniques * How my recipe differs from competitors * Troubleshooting common issues other recipes don't address 4. **Optimized Blog Post Outline:** * **H1 Title:** * **Meta Description:** (under 160 characters) * **Full H2/H3 outline** (including "Why This Recipe Works", "Ingredients", "Step-by-Step Instructions", "Storage & Make-Ahead Tips") * **Recipe Schema Markup Elements:** * **Required Photo/Video Content:** 5. **User-Focused FAQ Section:** 3–5 related to '{topic}' 6. **Internal & External Linking Plan:** * **Internal:** 2-3 relevant recipes with anchor suggestions * **External:** 1-2 reputable sources for techniques or ingredient information 7. **E-E-A-T Enhancements:** * Recipe testing notes to include * Personal experience elements to highlight * Scientific explanation opportunities 8. **SEO Performance Metrics:** * Expected keyword difficulty (1-100) * Estimated monthly search volume * Content length recommendation * Recipe card optimization tips """, "plant_based": """ Act as an elite-level SEO strategist and content creator with deep expertise in plant-based and vegan food blogs. I run a blog about plant-based cooking, and my primary goal is to increase organic traffic, help people transition to more plant-based eating, and provide delicious alternatives to animal products. My target audience includes vegans, vegetarians, flexitarians, and the plant-curious. For the specific topic: '{topic}' Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles. I require the following, formatted in clean markdown: 1. **Strategic Keyword Analysis:** * **Primary Target Keyword:** * **Secondary Keywords:** 2-3 closely related, high-intent keywords. * **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases. * **Dietary Restriction Related Keywords:** (gluten-free, nut-free, soy-free, etc.) * **Search Intent Analysis:** (Recipe-seeking, Nutrition information, Substitution help, etc.) 2. **Competitive Landscape Overview (Top 3-5 Competitors):** * For each: * URL * Ingredient approach (whole foods vs. processed substitutes) * Nutritional information provided * User engagement factors 3. **Plant-Based Value Proposition:** * Health/nutritional benefits to highlight * Environmental/ethical angle if applicable * Taste/texture comparisons to non-vegan alternatives * Accessibility of ingredients 4. **Optimized Blog Post Outline:** * **H1 Title:** * **Meta Description:** (under 160 characters) * **Full H2/H3 outline** (including "Why Choose Plant-Based", "Ingredients & Substitutions", "Step-by-Step Instructions", "Nutritional Information") * **Recipe Schema Markup Elements:** * **Required Photo Content:** 5. **User-Focused FAQ Section:** 3–5 related to '{topic}' (focusing on common substitution questions) 6. **Internal & External Linking Plan:** * **Internal:** 2-3 relevant recipes with anchor suggestions * **External:** 1-2 reputable sources for nutritional information 7. **E-E-A-T Enhancements:** * Nutritional expertise to highlight * Personal experience with plant-based eating * Scientific/research citations to include 8. **SEO Performance Metrics:** * Expected keyword difficulty (1-100) * Estimated monthly search volume * Nutritional content optimization * Health claim compliance """, "keto": """ Act as an elite-level SEO strategist and content creator with deep expertise in keto and low-carb food blogs. I run a blog about ketogenic recipes and lifestyle, and my primary goal is to increase organic traffic, help people succeed on keto, and provide delicious low-carb alternatives. My target audience includes keto beginners, experienced keto dieters, and low-carb enthusiasts. For the specific topic: '{topic}' Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles. I require the following, formatted in clean markdown: 1. **Strategic Keyword Analysis:** * **Primary Target Keyword:** * **Secondary Keywords:** 2-3 closely related, high-intent keywords. * **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases. * **Keto-Specific Keywords:** (net carbs, macros, ketosis, etc.) * **Search Intent Analysis:** (Recipe-seeking, Macro information, Keto compliance, etc.) 2. **Competitive Landscape Overview (Top 3-5 Competitors):** * For each: * URL * Macro accuracy and presentation * Keto compliance verification * User engagement factors 3. **Keto Value Proposition:** * Net carb calculations * Macro breakdown (fat/protein/carb ratios) * Ketone production potential * Satiety and weight loss benefits 4. **Optimized Blog Post Outline:** * **H1 Title:** * **Meta Description:** (under 160 characters) * **Full H2/H3 outline** (including "Why This Recipe is Keto", "Ingredients & Net Carbs", "Step-by-Step Instructions", "Macro Information") * **Recipe Schema Markup Elements:** * **Required Macro Charts/Tables:** 5. **User-Focused FAQ Section:** 3–5 related to '{topic}' (focusing on keto compliance questions) 6. **Internal & External Linking Plan:** * **Internal:** 2-3 relevant keto recipes with anchor suggestions * **External:** 1-2 reputable sources for nutritional/keto information 7. **E-E-A-T Enhancements:** * Nutritional expertise to highlight * Personal keto experience elements * Scientific/research citations for keto benefits 8. **SEO Performance Metrics:** * Expected keyword difficulty (1-100) * Estimated monthly search volume * Macro accuracy requirements * Keto community engagement potential """, "mediterranean": """ Act as an elite-level SEO strategist and content creator with deep expertise in Mediterranean cuisine and healthy food blogs. I run a blog about Mediterranean cooking and lifestyle, and my primary goal is to increase organic traffic, promote healthy eating habits, and share authentic Mediterranean recipes. My target audience includes health-conscious individuals, Mediterranean diet followers, and those interested in longevity and wellness. For the specific topic: '{topic}' Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles. I require the following, formatted in clean markdown: 1. **Strategic Keyword Analysis:** * **Primary Target Keyword:** * **Secondary Keywords:** 2-3 closely related, high-intent keywords. * **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases. * **Health-Focused Keywords:** (heart-healthy, anti-inflammatory, longevity, etc.) * **Search Intent Analysis:** (Recipe-seeking, Health information, Cultural learning, etc.) 2. **Competitive Landscape Overview (Top 3-5 Competitors):** * For each: * URL * Authenticity approach * Health benefit emphasis * Cultural storytelling elements 3. **Mediterranean Value Proposition:** * Health benefits (heart health, longevity, etc.) * Cultural authenticity and traditions * Ingredient quality and sourcing * Lifestyle integration aspects 4. **Optimized Blog Post Outline:** * **H1 Title:** * **Meta Description:** (under 160 characters) * **Full H2/H3 outline** (including "Mediterranean Diet Benefits", "Authentic Ingredients", "Step-by-Step Instructions", "Cultural Context") * **Recipe Schema Markup Elements:** * **Required Cultural/Historical Context:** 5. **User-Focused FAQ Section:** 3–5 related to '{topic}' (focusing on health and authenticity questions) 6. **Internal & External Linking Plan:** * **Internal:** 2-3 relevant Mediterranean recipes with anchor suggestions * **External:** 1-2 reputable sources for health research or cultural information 7. **E-E-A-T Enhancements:** * Cultural expertise or travel experience * Health research citations * Traditional cooking method explanations 8. **SEO Performance Metrics:** * Expected keyword difficulty (1-100) * Estimated monthly search volume * Health content optimization * Cultural authenticity factors """, "desserts": """ Act as an elite-level SEO strategist and content creator with deep expertise in dessert and pastry blogs. I run a blog about desserts and sweet treats, and my primary goal is to increase organic traffic, help home bakers create impressive desserts, and share both classic and innovative sweet recipes. My target audience includes dessert lovers, home bakers, and those looking for special occasion treats. For the specific topic: '{topic}' Analyze and generate a comprehensive SEO content plan designed to rank highly on Google and provide exceptional user value. Ensure all outputs adhere to E-E-A-T principles. I require the following, formatted in clean markdown: 1. **Strategic Keyword Analysis:** * **Primary Target Keyword:** * **Secondary Keywords:** 2-3 closely related, high-intent keywords. * **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases. * **Occasion-Specific Keywords:** (birthday, holiday, celebration, etc.) * **Search Intent Analysis:** (Recipe-seeking, Technique learning, Decoration ideas, etc.) 2. **Competitive Landscape Overview (Top 3-5 Competitors):** * For each: * URL * Visual presentation quality * Technique explanation depth * User engagement factors 3. **Dessert Value Proposition:** * Difficulty level and skill requirements * Visual appeal and presentation * Flavor profiles and uniqueness * Make-ahead and storage options 4. **Optimized Blog Post Outline:** * **H1 Title:** * **Meta Description:** (under 160 characters) * **Full H2/H3 outline** (including "Why This Dessert Works", "Ingredients & Substitutions", "Step-by-Step Instructions", "Decoration Tips", "Storage & Serving") * **Recipe Schema Markup Elements:** * **Required Photo/Video Content:** 5. **User-Focused FAQ Section:** 3–5 related to '{topic}' (focusing on technique and troubleshooting questions) 6. **Internal & External Linking Plan:** * **Internal:** 2-3 relevant dessert recipes with anchor suggestions * **External:** 1-2 reputable sources for technique or ingredient information 7. **E-E-A-T Enhancements:** * Baking expertise and testing notes * Personal experience with techniques * Scientific explanations for baking chemistry 8. **SEO Performance Metrics:** * Expected keyword difficulty (1-100) * Estimated monthly search volume * Visual content requirements * Seasonal/occasion optimization """ } # Enhanced language settings with keyword suggestions LANGUAGE_SETTINGS = { "English": { "search_engines": ["Google", "Bing", "DuckDuckGo"], "localization_tips": "Focus on English-speaking markets (US, UK, Canada, Australia)", "keyword_examples": ["recipe", "how to", "benefits of", "best", "easy", "homemade", "healthy", "quick", "simple", "ultimate"], "long_tail_patterns": ["how to make", "best way to", "easy recipe for", "homemade", "step by step", "beginner's guide to"], "question_keywords": ["what is", "why does", "how long", "can you", "is it safe", "what are the benefits"] }, "Spanish": { "search_engines": ["Google", "Bing", "Yahoo"], "localization_tips": "Target Spain and Latin American markets with regional variants", "keyword_examples": ["receta", "cómo hacer", "beneficios de", "mejor", "fácil", "casero", "saludable", "rápido", "sencillo", "definitivo"], "long_tail_patterns": ["cómo hacer", "mejor manera de", "receta fácil de", "casero", "paso a paso", "guía para principiantes"], "question_keywords": ["qué es", "por qué", "cuánto tiempo", "se puede", "es seguro", "cuáles son los beneficios"] }, "French": { "search_engines": ["Google", "Qwant", "Bing"], "localization_tips": "Focus on France, Belgium, Canada (Quebec), Switzerland", "keyword_examples": ["recette", "comment faire", "avantages de", "meilleur", "facile", "fait maison", "sain", "rapide", "simple", "ultime"], "long_tail_patterns": ["comment faire", "meilleure façon de", "recette facile de", "fait maison", "étape par étape", "guide pour débutants"], "question_keywords": ["qu'est-ce que", "pourquoi", "combien de temps", "peut-on", "est-ce sûr", "quels sont les avantages"] }, "German": { "search_engines": ["Google", "Bing", "Yahoo"], "localization_tips": "Target Germany, Austria, Switzerland with appropriate dialect considerations", "keyword_examples": ["rezept", "wie man", "vorteile von", "beste", "einfach", "hausgemacht", "gesund", "schnell", "einfach", "ultimativ"], "long_tail_patterns": ["wie man macht", "beste Art zu", "einfaches Rezept für", "hausgemacht", "Schritt für Schritt", "Anfängerführer für"], "question_keywords": ["was ist", "warum", "wie lange", "kann man", "ist es sicher", "was sind die Vorteile"] }, "Italian": { "search_engines": ["Google", "Bing", "Yahoo"], "localization_tips": "Target Italy with regional food variations and local ingredients", "keyword_examples": ["ricetta", "come fare", "benefici di", "migliore", "facile", "fatto in casa", "sano", "veloce", "semplice", "perfetto"], "long_tail_patterns": ["come fare", "modo migliore per", "ricetta facile di", "fatto in casa", "passo dopo passo", "guida per principianti"], "question_keywords": ["cos'è", "perché", "quanto tempo", "si può", "è sicuro", "quali sono i benefici"] } } # Function to save templates to file def save_templates(): with open("templates.json", "w") as f: json.dump(DEFAULT_TEMPLATES, f, indent=4) with open("languages.json", "w") as f: json.dump(LANGUAGE_SETTINGS, f, indent=4) # Load templates if they exist, otherwise use defaults def load_templates(): templates = DEFAULT_TEMPLATES.copy() languages = LANGUAGE_SETTINGS.copy() try: if os.path.exists("templates.json"): with open("templates.json", "r") as f: templates = json.load(f) except Exception as e: print(f"Error loading templates: {e}") try: if os.path.exists("languages.json"): with open("languages.json", "r") as f: languages = json.load(f) except Exception as e: print(f"Error loading languages: {e}") return templates, languages # Initialize templates TEMPLATES, LANGUAGES = load_templates() # Enhanced HTML export with better styling and SEO metrics def generate_html_export(content, title, template_type, language): # content here is expected to be MARKDOWN html_template = f"""
Your comprehensive SEO plan will appear here...
" or markdown_content == "Your comprehensive SEO plan will appear here...": return "Please generate an SEO plan first.", None title = topic.strip().title() html_content_to_save = generate_html_export(markdown_content, title, template_type, language) safe_filename = "".join([c if c.isalnum() or c in " -_" else "_" for c in title]) safe_filename = f"{safe_filename}_{template_type}_{language}_Styled_SEO_Plan.html".replace(" ", "_") try: with open(safe_filename, "w", encoding="utf-8") as f: f.write(html_content_to_save) return f"✅ Styled HTML export saved as '{safe_filename}'", safe_filename except Exception as e: return f"❌ Error saving styled HTML file: {str(e)}", None # Export the DISPLAYED HTML content (which is already HTML) def export_displayed_html(html_content, topic): # html_content is the HTML string from the gr.HTML component placeholder_html = "Your comprehensive SEO plan will appear here...
" if not html_content or html_content == placeholder_html or html_content.startswith("⚠️") or html_content.startswith("🔄") or html_content.startswith("📝") or html_content.startswith("✨") or html_content.startswith("🧠") or html_content.startswith("🚀"): # Check for various states return "Please generate and finalize an SEO plan first.", None title = topic.strip().title() if topic.strip() else "Generated_Content" safe_filename = "".join([c if c.isalnum() or c in " -_" else "_" for c in title]) safe_filename = f"{safe_filename}_Displayed_Content.html".replace(" ", "_") try: with open(safe_filename, "w", encoding="utf-8") as f: f.write(html_content) return f"✅ Displayed HTML content saved as '{safe_filename}'", safe_filename except Exception as e: return f"❌ Error saving displayed HTML file: {str(e)}", None # Enhanced template management def save_custom_template(template_name, template_content): if not template_name or not template_content: return "⚠️ Please provide both a template name and content." TEMPLATES[template_name.lower().replace(" ", "_")] = template_content save_templates() return f"✅ Template '{template_name}' saved successfully!" def delete_template(template_name): if template_name in TEMPLATES: if template_name in DEFAULT_TEMPLATES: return "⚠️ Cannot delete default templates." del TEMPLATES[template_name] save_templates() return f"✅ Template '{template_name}' deleted successfully!" else: return f"⚠️ Template '{template_name}' not found." def load_template_content(template_name): if template_name in TEMPLATES: return TEMPLATES[template_name] return "" def get_template_list(): return list(TEMPLATES.keys()) # Enhanced language settings management def save_language_settings(language_name, search_engines, localization_tips, keyword_examples, long_tail_patterns, question_keywords): if not language_name: return "⚠️ Please provide a language name." search_engines_list = [se.strip() for se in search_engines.split(",") if se.strip()] keyword_examples_list = [kw.strip() for kw in keyword_examples.split(",") if kw.strip()] long_tail_list = [lt.strip() for lt in long_tail_patterns.split(",") if lt.strip()] question_list = [q.strip() for q in question_keywords.split(",") if q.strip()] LANGUAGES[language_name] = { "search_engines": search_engines_list, "localization_tips": localization_tips, "keyword_examples": keyword_examples_list, "long_tail_patterns": long_tail_list, "question_keywords": question_list } save_templates() return f"✅ Language settings for '{language_name}' saved successfully!" # Enhanced prompt building with advanced features def build_prompt(topic, template_key="fermentation", language="English", include_advanced_metrics=True): if template_key in TEMPLATES: template = TEMPLATES[template_key] else: template = TEMPLATES["fermentation"] lang_settings = LANGUAGES.get(language, LANGUAGES["English"]) language_instructions = f""" LANGUAGE & LOCALIZATION OPTIMIZATION FOR {language.upper()}: 1. **Target Search Engines:** {', '.join(lang_settings['search_engines'])} 2. **Localization Strategy:** {lang_settings['localization_tips']} 3. **Primary Keyword Patterns:** {', '.join(lang_settings['keyword_examples'])} 4. **Long-tail Keyword Patterns:** {', '.join(lang_settings.get('long_tail_patterns', []))} 5. **Question-based Keywords:** {', '.join(lang_settings.get('question_keywords', []))} """ if include_advanced_metrics: advanced_metrics = """ ADVANCED SEO METRICS TO INCLUDE: 9. **Content Performance Analysis:** * Recommended content length (word count) * Target reading time * Keyword density recommendations * Readability score target (Flesch-Kincaid) * Mobile optimization considerations 10. **AI-Powered Content Suggestions:** * Trending subtopics to include * Related questions people are asking * Seasonal content opportunities * Social media content ideas * Email marketing angles 11. **Technical SEO Considerations:** * Page speed optimization tips * Image optimization requirements * Schema markup recommendations * Internal linking architecture * URL structure suggestions 12. **Content Distribution Strategy:** * Social media promotion angles * Email newsletter content ideas * Pinterest optimization tips * YouTube video content suggestions * Podcast episode ideas """ else: advanced_metrics = "" if language != "English": full_template = template + "\n\n" + language_instructions + advanced_metrics else: full_template = template + "\n\n" + advanced_metrics return full_template.format(topic=topic) # Enhanced SEO generation with streaming (YIELDS MARKDOWN) def generate_seo_plan(topic, api_key, template_key="fermentation", language="English", temperature=0.7, max_tokens=6000, include_advanced_metrics=True): if not topic.strip(): yield "⚠️ Please enter a topic to generate an SEO plan." return if not api_key.strip(): yield "⚠️ Please provide your Gemini API key." return yield "🔄 Initializing Enhanced SEO Assistant..." try: genai.configure(api_key=api_key) model = genai.GenerativeModel( "gemini-1.5-pro", generation_config={ "temperature": float(temperature), "max_output_tokens": max_tokens, "top_p": 0.95, "top_k": 40 } ) yield f"🧠 Building enhanced SEO prompt for {template_key} niche in {language}..." prompt = build_prompt(topic, template_key, language, include_advanced_metrics) yield "🚀 Generating comprehensive SEO plan with Gemini 1.5 Pro..." response = model.generate_content(prompt, stream=True) full_response = "" for chunk in response: if chunk.text: full_response += chunk.text yield "📝 " + full_response yield "✨ Finalizing your enhanced SEO plan..." time.sleep(0.5) yield full_response # This is the final MARKDOWN except Exception as e: error_message = str(e) print(f"Error generating SEO plan: {error_message}") if "API key not valid" in error_message or "authentication" in error_message.lower(): yield "⚠️ API Key Error: The provided Gemini API key appears to be invalid. Please check your key and try again." elif "quota" in error_message.lower(): yield "⚠️ Quota Exceeded: Your Gemini API quota has been exceeded. Please check your Google AI Studio dashboard." else: yield f"⚠️ Error: {error_message}" # AI-powered content suggestions (RETURNS MARKDOWN) def generate_content_ideas(topic, api_key, template_key="fermentation", language="English"): if not topic.strip() or not api_key.strip(): return "⚠️ Please provide both a topic and API key." try: genai.configure(api_key=api_key) model = genai.GenerativeModel("gemini-1.5-pro") prompt = f""" As an AI content strategist specializing in {template_key} content, generate creative content ideas for the topic: "{topic}" Please provide: 1. **5 Related Blog Post Ideas:** - Complementary topics that would work well together - Different angles on the same subject 2. **Social Media Content Ideas:** - 3 Instagram post concepts - 3 TikTok/Reel ideas - 2 Pinterest pin concepts 3. **Email Marketing Angles:** - Welcome series email ideas - Newsletter content suggestions 4. **Video Content Opportunities:** - YouTube video concepts - Short-form video ideas 5. **Seasonal Content Calendar:** - Monthly content themes - Holiday tie-ins 6. **User-Generated Content Ideas:** - Contest/challenge concepts - Community engagement strategies Format in clean markdown with actionable suggestions. """ response = model.generate_content(prompt) return response.text except Exception as e: return f"⚠️ Error generating content ideas: {str(e)}" # Keyword research enhancement (RETURNS MARKDOWN) def generate_keyword_research(topic, api_key, language="English", competition_level="medium"): if not topic.strip() or not api_key.strip(): return "⚠️ Please provide both a topic and API key." try: genai.configure(api_key=api_key) model = genai.GenerativeModel("gemini-1.5-pro") lang_settings = LANGUAGES.get(language, LANGUAGES["English"]) prompt = f""" As an SEO keyword research specialist, provide comprehensive keyword analysis for: "{topic}" in {language} Target competition level: {competition_level} Please provide: 1. **Primary Keywords (3-5):** - High search volume, {competition_level} competition - Include estimated monthly searches 2. **Long-tail Keywords (10-15):** - Lower competition, more specific - Question-based keywords using patterns: {', '.join(lang_settings.get('question_keywords', []))} 3. **Semantic Keywords (8-10):** - Related terms and synonyms - LSI keywords for content depth 4. **Local SEO Keywords (if applicable):** - Location-based variations - "Near me" variations 5. **Competitor Keywords:** - What competitors are likely ranking for - Keyword gaps to exploit 6. **Trending Keywords:** - Seasonal trends - Emerging topics in this niche 7. **Conversion-Focused Keywords:** - Commercial intent keywords - Buyer journey keywords Provide keyword difficulty estimates (1-100) and search volume estimates for each category. Format in clean markdown with actionable insights. """ response = model.generate_content(prompt) return response.text except Exception as e: return f"⚠️ Error generating keyword research: {str(e)}" # Wrapper for generate_seo_plan to handle streaming and HTML conversion def stream_and_convert_seo_plan_wrapper(topic, api_key, template_key, language, temperature, max_tokens, include_advanced_metrics): latest_raw_markdown = "" initial_placeholder_html = "Your comprehensive SEO plan will appear here...
" # Used to avoid processing placeholder for output_from_generator in generate_seo_plan(topic, api_key, template_key, language, temperature, max_tokens, include_advanced_metrics): display_content_for_html_component = initial_placeholder_html current_markdown_for_state = latest_raw_markdown if output_from_generator.startswith("🔄") or \ output_from_generator.startswith("🧠") or \ output_from_generator.startswith("🚀") or \ output_from_generator.startswith("✨"): display_content_for_html_component = output_from_generator # Status messages as text elif output_from_generator.startswith("📝 "): actual_markdown = output_from_generator[2:] latest_raw_markdown = actual_markdown current_markdown_for_state = actual_markdown display_content_for_html_component = "📝 Processing... please wait.
" + markdown.markdown(actual_markdown) # Show prefix, then HTML elif output_from_generator.startswith("⚠️"): display_content_for_html_component = output_from_generator # Error messages as text latest_raw_markdown = output_from_generator current_markdown_for_state = output_from_generator else: # Final, complete markdown block latest_raw_markdown = output_from_generator current_markdown_for_state = output_from_generator display_content_for_html_component = markdown.markdown(output_from_generator) yield { outputs_map["seo_output"]: display_content_for_html_component, outputs_map["raw_seo_markdown_state"]: current_markdown_for_state } # Final yield to ensure state is correct if latest_raw_markdown: final_display = markdown.markdown(latest_raw_markdown) if not latest_raw_markdown.startswith("⚠️") else latest_raw_markdown yield { outputs_map["seo_output"]: final_display, outputs_map["raw_seo_markdown_state"]: latest_raw_markdown } # Wrapper for non-streaming functions to convert MD to HTML and update states def convert_md_to_html_for_output(fn_generating_markdown, *args): markdown_content = fn_generating_markdown(*args) html_content = "" if markdown_content.startswith("⚠️"): html_content = markdown_content # Pass error message as is else: html_content = markdown.markdown(markdown_content) # Returns a dictionary for multiple outputs return html_content, markdown_content # Function to clear outputs def clear_outputs_fn(): return { inputs_map["topic_input"]: "", outputs_map["seo_output"]: "Your comprehensive SEO plan will appear here...
", outputs_map["keyword_output"]: "Your keyword research will appear here...
", outputs_map["content_ideas_output"]: "Your content ideas will appear here...
", outputs_map["raw_seo_markdown_state"]: "", outputs_map["raw_keyword_markdown_state"]: "", outputs_map["raw_content_ideas_markdown_state"]: "", outputs_map["export_status"]: "", outputs_map["download_file"]: None, outputs_map["download_displayed_file"]: None, } # Save API key to user's preferences def save_api_key(api_key): if api_key.strip(): with open(".env", "w") as f: f.write(f"GEMINI_API_KEY={api_key}") return "✅ API key saved successfully!" return "⚠️ Please enter an API key to save" # Enhanced theme custom_theme = gr.themes.Soft( primary_hue="blue", secondary_hue="purple", ).set( body_text_color="#2d3748", block_title_text_weight="600", button_primary_background_fill="linear-gradient(90deg, #667eea 0%, #764ba2 100%)", button_primary_background_fill_hover="linear-gradient(90deg, #764ba2 0%, #667eea 100%)", button_primary_text_color="white", block_label_text_size="0.9rem", block_title_text_size="1.2rem" ) # background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); # Main Gradio app with 6 organized sections with gr.Blocks(title="Enhanced SEO Assistant", theme=custom_theme, css=""" .main-container { max-width: 1200px; margin: 0 auto; } .section-header { background: #2563eb; color: white; padding: 15px; border-radius: 8px; margin: 20px 0 10px 0; text-align: center; font-weight: bold; } .feature-box { border: 2px solid #e2e8f0; border-radius: 8px; padding: 20px; margin: 10px 0; background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%); } .output-container { min-height: 400px; max-height: 800px; overflow-y: auto; border-left: 4px solid #667eea; padding: 20px; border-radius: 8px; margin: 10px 0; } .metrics-display { background: linear-gradient(135deg, #fed7d7 0%, #fbb6ce 100%); border-radius: 8px; padding: 15px; margin: 10px 0; } """) as app: # Header gr.Markdown(""" # 🚀 Enhanced SEO Content Assistant ### AI-Powered Content Strategy for Food Bloggers & Content Creators Generate comprehensive SEO plans, keyword research, and content ideas using Google's Gemini 1.5 Pro. Rendered content is in HTML. You can download the styled export (from original Markdown) or the displayed HTML. """) # For mapping inputs/outputs in functions like clear_outputs_fn inputs_map = {} outputs_map = {} # ============== SECTION 1: API Configuration & Settings ============== with gr.Group(): gr.HTML('Your comprehensive SEO plan will appear here...
", elem_classes=["output-container"]) outputs_map["seo_output"] = seo_output raw_seo_markdown_state = gr.Textbox(visible=False, label="Raw SEO Markdown") # Hidden state outputs_map["raw_seo_markdown_state"] = raw_seo_markdown_state # ============== SECTION 4: Export & Download Options ============== with gr.Group(): gr.HTML('Your keyword research will appear here...
", elem_classes=["output-container"]) outputs_map["keyword_output"] = keyword_output raw_keyword_markdown_state = gr.Textbox(visible=False, label="Raw Keyword Markdown") # Hidden state outputs_map["raw_keyword_markdown_state"] = raw_keyword_markdown_state with gr.Tab("💡 Content Ideas"): content_ideas_topic = gr.Textbox(label="Topic for Content Ideas", placeholder="Enter topic for content brainstorming") inputs_map["content_ideas_topic"] = content_ideas_topic content_ideas_btn = gr.Button("💡 Generate Content Ideas") content_ideas_output = gr.HTML(value="Your content ideas will appear here...
", elem_classes=["output-container"]) outputs_map["content_ideas_output"] = content_ideas_output raw_content_ideas_markdown_state = gr.Textbox(visible=False, label="Raw Content Ideas Markdown") # Hidden state outputs_map["raw_content_ideas_markdown_state"] = raw_content_ideas_markdown_state with gr.Tab("📊 SEO Metrics"): gr.Markdown("""### 📈 SEO Performance Metrics Included: - **Keyword Difficulty Analysis**: Competition assessment (1-100) - **Search Volume Estimates**: Monthly search predictions - **Content Length Recommendations**: Optimal word count - **Readability Targets**: Flesch-Kincaid score goals - **Technical SEO Checklist**: Page speed, schema markup - **Mobile Optimization**: Responsive design considerations""") # ============== SECTION 6: Language & Localization Settings ============== with gr.Group(): gr.HTML('