FermentationSEO / app.py
mroccuper's picture
Update app.py
a2e798a verified
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"""<!DOCTYPE html>
<html lang="{language.lower()[:2]}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title} - SEO Plan</title>
<style>
body {{
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #333;
max-width: 1000px;
margin: 0 auto;
padding: 20px;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}}
.container {{
background-color: white;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0,0,0,0.1);
overflow: hidden;
}}
header {{
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}}
.header-info {{
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 20px;
font-size: 0.9em;
opacity: 0.9;
}}
h1 {{
margin: 0;
font-size: 2.2em;
font-weight: 300;
}}
h2 {{
border-bottom: 3px solid #667eea;
padding-bottom: 10px;
color: #4c51bf;
margin-top: 30px;
}}
h3 {{
color: #553c9a;
margin-top: 25px;
}}
.content {{
padding: 40px;
}}
.metrics-box {{
background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
padding: 20px;
border-radius: 8px;
margin: 20px 0;
border-left: 5px solid #f56565;
}}
.keyword-box {{
background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
padding: 15px;
border-radius: 8px;
margin: 15px 0;
}}
ul {{
margin-left: 20px;
}}
li {{
margin-bottom: 8px;
padding-left: 5px;
}}
code {{
background-color: #f7fafc;
padding: 3px 6px;
border-radius: 4px;
font-family: 'Monaco', 'Consolas', monospace;
border: 1px solid #e2e8f0;
}}
blockquote {{
border-left: 4px solid #667eea;
margin-left: 0;
padding-left: 20px;
color: #4a5568;
font-style: italic;
background-color: #f7fafc;
padding: 15px 20px;
border-radius: 0 8px 8px 0;
}}
.export-info {{
background-color: #edf2f7;
padding: 20px;
border-radius: 8px;
margin: 20px 0;
border: 1px solid #cbd5e0;
}}
footer {{
background-color: #2d3748;
color: white;
padding: 20px;
text-align: center;
}}
.print-button {{
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
margin: 10px;
}}
@media print {{
body {{ background: white; }}
.container {{ box-shadow: none; }}
.print-button {{ display: none; }}
}}
</style>
</head>
<body>
<div class="container">
<header>
<h1>{title} - SEO Content Strategy</h1>
<div class="header-info">
<span>πŸ“Š Template: {template_type.title()}</span>
<span>🌐 Language: {language}</span>
<span>πŸ“… Generated: {datetime.now().strftime("%B %d, %Y at %H:%M")}</span>
</div>
</header>
<div class="content">
<div class="export-info">
<strong>πŸ“‹ Export Information:</strong><br>
This SEO plan was generated using AI analysis and industry best practices.
Use this as a strategic guide for your content creation process.
<button class="print-button" onclick="window.print()">πŸ–¨οΈ Print/Save as PDF</button>
</div>
{markdown.markdown(content)}
</div>
<footer>
<p>πŸš€ Generated using Enhanced SEO Assistant |
Template: {template_type.title()} |
Language: {language} |
AI-Powered Content Strategy</p>
</footer>
</div>
<script>
// Add some interactivity
document.addEventListener('DOMContentLoaded', function() {{
// Highlight keywords in content
const keywords = document.querySelectorAll('code');
keywords.forEach(keyword => {{
keyword.style.cursor = 'pointer';
keyword.addEventListener('click', function() {{
navigator.clipboard.writeText(this.textContent);
this.style.backgroundColor = '#48bb78';
this.style.color = 'white';
setTimeout(() => {{
this.style.backgroundColor = '#f7fafc';
this.style.color = '#2d3748';
}}, 1000);
}});
}});
}});
</script>
</body>
</html>
"""
return html_template
# Export the SEO plan as STYLED HTML and create download link
def export_styled_html(markdown_content, topic, template_type, language):
# markdown_content is the raw markdown from the AI
if not markdown_content or markdown_content.startswith("⚠️") or markdown_content.startswith("πŸ”„") or markdown_content == "<p>Your comprehensive SEO plan will appear here...</p>" 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 = "<p>Your comprehensive SEO plan will appear here...</p>"
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 = "<p>Your comprehensive SEO plan will appear here...</p>" # 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 = "<p>πŸ“ Processing... please wait.</p>" + 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"]: "<p>Your comprehensive SEO plan will appear here...</p>",
outputs_map["keyword_output"]: "<p>Your keyword research will appear here...</p>",
outputs_map["content_ideas_output"]: "<p>Your content ideas will appear here...</p>",
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('<div class="section-header">πŸ”§ Section 1: API Configuration & Settings</div>')
with gr.Row():
with gr.Column(scale=2):
api_key_input = gr.Textbox(label="πŸ”‘ Gemini API Key", placeholder="Enter your Google Gemini API key", value=os.getenv("GEMINI_API_KEY", ""), type="password")
inputs_map["api_key_input"] = api_key_input
with gr.Column(scale=1):
save_api_btn = gr.Button("πŸ’Ύ Save Key", variant="secondary")
api_status = gr.Textbox(label="Status", interactive=False, max_lines=1)
outputs_map["api_status"] = api_status
with gr.Row():
with gr.Column():
#gr.Markdown("### πŸŽ›οΈ Advanced Settings")
temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, label="Temperature (Creativity)", info="Higher = more creative, Lower = more focused")
inputs_map["temperature"] = temperature
with gr.Column():
max_tokens = gr.Slider(minimum=2000, maximum=8000, value=6000, step=500, label="Max Output Length", info="Maximum response length")
inputs_map["max_tokens"] = max_tokens
with gr.Column():
include_advanced = gr.Checkbox(label="Include Advanced Metrics", value=True, info="Include technical SEO and content distribution strategies")
inputs_map["include_advanced"] = include_advanced
# ============== SECTION 2: Template & Language Selection ==============
with gr.Group():
gr.HTML('<div class="section-header">🎯 Section 2: Template & Language Selection</div>')
with gr.Row():
with gr.Column():
template_dropdown = gr.Dropdown(choices=list(TEMPLATES.keys()), value="fermentation", label="🍽️ Content Template", info="Choose your food niche template")
inputs_map["template_dropdown"] = template_dropdown
with gr.Column():
language_dropdown = gr.Dropdown(choices=list(LANGUAGES.keys()), value="English", label="🌐 Target Language", info="Optimize for specific language/region")
inputs_map["language_dropdown"] = language_dropdown
with gr.Accordion("πŸ“ Template Management", open=False):
with gr.Row():
with gr.Column():
custom_template_name = gr.Textbox(label="Template Name", placeholder="e.g., my_custom_template")
inputs_map["custom_template_name"] = custom_template_name
custom_template_content = gr.Textbox(label="Template Content", placeholder="Enter your custom template with {topic} placeholder", lines=10)
inputs_map["custom_template_content"] = custom_template_content
save_template_btn = gr.Button("πŸ’Ύ Save Custom Template")
template_status = gr.Textbox(label="Template Status", interactive=False)
outputs_map["template_status"] = template_status
with gr.Column():
template_preview = gr.Textbox(label="Template Preview", placeholder="Select a template to preview", lines=10, interactive=False)
outputs_map["template_preview"] = template_preview
load_template_btn = gr.Button("πŸ‘€ Preview Selected Template")
# ============== SECTION 3: Main SEO Plan Generation ==============
with gr.Group():
gr.HTML('<div class="section-header">✨ Section 3: SEO Plan Generation</div>')
with gr.Row():
with gr.Column(scale=1):
topic_input = gr.Textbox(label="🎯 Your Content Topic", placeholder="e.g., Ultimate Guide to Homemade Kimchi", lines=3)
inputs_map["topic_input"] = topic_input
with gr.Row():
generate_btn = gr.Button("πŸš€ Generate SEO Plan", variant="primary", size="lg")
clear_btn = gr.Button("πŸ”„ Clear All", variant="secondary")
gr.Examples(examples=["Beginner's Guide to Fermenting Vegetables at Home", "Perfect Sourdough Starter: Science and Technique", "Keto-Friendly Fermented Foods for Weight Loss"], inputs=topic_input, label="πŸ’‘ Example Topics")
with gr.Column(scale=2):
seo_output = gr.HTML(value="<p>Your comprehensive SEO plan will appear here...</p>", 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('<div class="section-header">πŸ“€ Section 4: Export & Download Options</div>')
with gr.Row():
with gr.Column():
export_styled_html_btn = gr.Button("πŸ“„ Export Styled HTML (from Markdown)", variant="primary")
download_displayed_html_btn = gr.Button("πŸ“„ Download Displayed HTML", variant="secondary")
export_status = gr.Textbox(label="Export Status", interactive=False)
outputs_map["export_status"] = export_status
with gr.Column():
download_file = gr.File(label="πŸ“₯ Download Styled Export File", interactive=False)
outputs_map["download_file"] = download_file
download_displayed_file = gr.File(label="πŸ“₯ Download Displayed HTML File", interactive=False) # New file component
outputs_map["download_displayed_file"] = download_displayed_file
gr.Markdown("""### πŸ“‹ Export Features:
- **Styled HTML Export**: Professional, printable SEO plans from original Markdown.
- **Displayed HTML Download**: Download the exact HTML rendered in the main output area.
- **Template Information**: Includes template type and language used in styled export.
- **Print-Friendly**: Styled export is optimized for PDF.
- **Interactive Elements**: Clickable keywords in styled export.""")
# ============== SECTION 5: Advanced SEO Tools ==============
with gr.Group():
gr.HTML('<div class="section-header">πŸ” Section 5: Advanced SEO Tools</div>')
with gr.Tabs():
with gr.Tab("🎯 Keyword Research"):
with gr.Row():
keyword_topic = gr.Textbox(label="Topic for Keyword Research", placeholder="Enter topic for keyword analysis")
inputs_map["keyword_topic"] = keyword_topic
competition_level = gr.Dropdown(choices=["low", "medium", "high"], value="medium", label="Competition Level")
inputs_map["competition_level"] = competition_level
keyword_research_btn = gr.Button("πŸ” Generate Keyword Report")
keyword_output = gr.HTML(value="<p>Your keyword research will appear here...</p>", 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="<p>Your content ideas will appear here...</p>", 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('<div class="section-header">🌍 Section 6: Language & Localization Settings</div>')
with gr.Accordion("πŸ”§ Language Settings Management", open=False):
with gr.Row():
with gr.Column():
lang_name = gr.Textbox(label="Language Name", placeholder="e.g., Portuguese")
inputs_map["lang_name"] = lang_name
search_engines = gr.Textbox(label="Search Engines", placeholder="Google, Bing, Yahoo (comma-separated)")
inputs_map["search_engines"] = search_engines
localization_tips = gr.Textbox(label="Localization Tips", placeholder="Regional considerations and market focus", lines=3)
inputs_map["localization_tips"] = localization_tips
with gr.Column():
keyword_examples_txt = gr.Textbox(label="Keyword Examples", placeholder="Common keywords (comma-separated)", lines=2) # Renamed to avoid conflict
inputs_map["keyword_examples_txt"] = keyword_examples_txt
long_tail_patterns_txt = gr.Textbox(label="Long-tail Patterns", placeholder="Common long-tail patterns (comma-separated)", lines=2) # Renamed
inputs_map["long_tail_patterns_txt"] = long_tail_patterns_txt
question_keywords_txt = gr.Textbox(label="Question Keywords", placeholder="Common question words (comma-separated)", lines=2) # Renamed
inputs_map["question_keywords_txt"] = question_keywords_txt
save_lang_btn = gr.Button("πŸ’Ύ Save Language Settings")
lang_status = gr.Textbox(label="Language Settings Status", interactive=False)
outputs_map["lang_status"] = lang_status
gr.Markdown("""### πŸ—ΊοΈ Current Language Support:
- **English**: US, UK, Canada, Australia markets
- **Spanish**: Spain and Latin American markets
- **French**: France, Belgium, Quebec, Switzerland
- **German**: Germany, Austria, Switzerland
- **Italian**: Italy with regional variations
Add more languages using the settings panel above!""")
# ============== EVENT HANDLERS ==============
save_api_btn.click(fn=save_api_key, inputs=api_key_input, outputs=api_status)
save_template_btn.click(fn=save_custom_template, inputs=[custom_template_name, custom_template_content], outputs=template_status)
load_template_btn.click(fn=load_template_content, inputs=template_dropdown, outputs=template_preview)
generate_btn.click(
fn=stream_and_convert_seo_plan_wrapper,
inputs=[topic_input, api_key_input, template_dropdown, language_dropdown, temperature, max_tokens, include_advanced],
outputs=[seo_output, raw_seo_markdown_state], # seo_output (HTML), raw_seo_markdown_state (Markdown)
show_progress="full"
)
export_styled_html_btn.click(
fn=export_styled_html,
inputs=[raw_seo_markdown_state, topic_input, template_dropdown, language_dropdown], # Use raw markdown state
outputs=[export_status, download_file]
)
download_displayed_html_btn.click(
fn=export_displayed_html,
inputs=[seo_output, topic_input], # seo_output contains HTML
outputs=[export_status, download_displayed_file] # Use new file component
)
def keyword_research_wrapper(topic, api_key, language, competition):
html_out, md_out = convert_md_to_html_for_output(generate_keyword_research, topic, api_key, language, competition)
return {keyword_output: html_out, raw_keyword_markdown_state: md_out}
keyword_research_btn.click(
fn=keyword_research_wrapper,
inputs=[keyword_topic, api_key_input, language_dropdown, competition_level],
outputs=[keyword_output, raw_keyword_markdown_state]
)
def content_ideas_wrapper(topic, api_key, template, language):
html_out, md_out = convert_md_to_html_for_output(generate_content_ideas, topic, api_key, template, language)
return {content_ideas_output: html_out, raw_content_ideas_markdown_state: md_out}
content_ideas_btn.click(
fn=content_ideas_wrapper,
inputs=[content_ideas_topic, api_key_input, template_dropdown, language_dropdown],
outputs=[content_ideas_output, raw_content_ideas_markdown_state]
)
save_lang_btn.click(
fn=save_language_settings,
inputs=[lang_name, search_engines, localization_tips, keyword_examples_txt, long_tail_patterns_txt, question_keywords_txt],
outputs=lang_status
)
clear_btn.click(
fn=clear_outputs_fn,
outputs=list(outputs_map.values()) + [inputs_map["topic_input"]] # Clear relevant outputs and the main topic input
)
gr.Markdown("""---
## πŸš€ Enhanced Features Overview
### ✨ What's New:
- **HTML Rendering**: Main content areas now render generated Markdown as HTML.
- **Download Displayed HTML**: Button to download the HTML shown in the output area.
- **Styled HTML Export**: Retained, uses original Markdown for professional, styled exports.
- **6 Organized Sections**: Better UX with logical feature grouping.
- **Custom Templates**: Create and manage your own templates.
- **Multiple Food Niches**: Fermentation, Baking, Plant-Based, Keto, Mediterranean, Desserts.
- **Advanced SEO Tools**: Keyword research and content idea generation.
- **Multi-Language Support**: Optimize for different markets and languages.
- **Enhanced Metrics**: Technical SEO, performance analysis, and content distribution.
### πŸ”— Useful Links:
- [Get Gemini API Key](https://aistudio.google.com/)
- [Gradio Documentation](https://gradio.app/docs/)
- [SEO Best Practices](https://developers.google.com/search/docs)
### πŸ” Privacy & Security:
Your API key is stored locally in a `.env` file (if you save it) and only used for Google AI services. No data is shared with third parties.""")
if __name__ == "__main__":
print("πŸš€ Starting Enhanced SEO Assistant...")
app.launch(
#share=True, # Set to False if you don't want public sharing
#debug=True,
#show_error=True,
#server_name="0.0.0.0",
#server_port=7860,
#quiet=False
)