import gradio as gr import google.generativeai as genai import re import html import base64 from datetime import datetime import json class FermentationSEOGenerator: def __init__(self): self.model = None def configure_gemini(self, api_key): """Configure Gemini API with the provided key""" try: genai.configure(api_key=api_key) self.model = genai.GenerativeModel('gemini-1.5-pro') return True, "API configured successfully!" except Exception as e: return False, f"API configuration failed: {str(e)}" def parse_internal_links(self, internal_links_text): """Parse internal links from keyword:link format""" links_dict = {} if internal_links_text.strip(): lines = internal_links_text.strip().split('\n') for line in lines: if ':' in line: parts = line.split(':', 1) if len(parts) == 2: keyword = parts[0].strip() link = parts[1].strip() links_dict[keyword] = link return links_dict def parse_extra_keywords(self, extra_keywords_text): """Parse extra keywords from text area""" keywords = [] if extra_keywords_text.strip(): keywords = [kw.strip() for kw in extra_keywords_text.strip().split('\n') if kw.strip()] return keywords def calculate_readability(self, text): """Calculate basic readability metrics""" # Remove HTML tags for readability calculation clean_text = re.sub(r'<[^>]+>', '', text) # Count sentences, words, and syllables sentences = len(re.findall(r'[.!?]+', clean_text)) words = len(clean_text.split()) # Rough syllable count syllables = sum([max(1, len(re.findall(r'[aeiouAEIOU]', word))) for word in clean_text.split()]) if sentences == 0 or words == 0: return {"flesch_score": 0, "grade_level": 0, "words": words, "sentences": sentences} # Flesch Reading Ease Score flesch_score = 206.835 - (1.015 * (words / sentences)) - (84.6 * (syllables / words)) # Flesch-Kincaid Grade Level grade_level = (0.39 * (words / sentences)) + (11.8 * (syllables / words)) - 15.59 return { "flesch_score": round(flesch_score, 1), "grade_level": round(max(0, grade_level), 1), "words": words, "sentences": sentences } def generate_seo_prompt(self, seo_plan, pov, tone, length, internal_links, extra_keywords, emotional_tone, generate_titles, include_readability): """Generate the comprehensive prompt for Gemini""" # Define content length targets length_targets = { "Short": "1500-2000 words", "Standard": "2500-3500 words", "Long Form": "4000-6000 words" } internal_links_str = "" if internal_links: internal_links_str = "\n".join([f"- {keyword}: {link}" for keyword, link in internal_links.items()]) extra_keywords_str = ", ".join(extra_keywords) if extra_keywords else "" prompt = f""" You are an expert SEO content writer specializing in fermentation and gut health. Create a comprehensive, high-quality article optimized for 2025 SEO standards. ARTICLE REQUIREMENTS: - Topic/SEO Plan: {seo_plan} - Target Length: {length_targets[length]} - Point of View: {pov} person - Tone: {tone} - Emotional Tone: {emotional_tone} - Niche Focus: Fermentation, gut health, probiotics, traditional food preservation INTERNAL LINKS TO NATURALLY INCORPORATE: {internal_links_str} ADDITIONAL KEYWORDS TO INCLUDE: {extra_keywords_str} 2025 SEO OPTIMIZATION REQUIREMENTS: 1. E-A-T Optimization: Include expert insights, scientific backing, personal experience elements 2. Featured Snippet Optimization: Use clear, concise answers to common questions 3. People Also Ask Integration: Address related questions naturally within content 4. Semantic SEO: Use related terms and context-rich language 5. User Intent Focus: Solve real problems and provide actionable advice CONTENT STRUCTURE REQUIREMENTS: - Compelling H1 with primary keyword - Logical H2/H3 hierarchy with keyword variations - Meta title (50-60 characters) and meta description (150-160 characters) - Introduction hook with clear value proposition - Step-by-step instructions where applicable - Expert tips and troubleshooting sections - FAQ section addressing common concerns - Strong conclusion with call-to-action WRITING STYLE: - Human-like, conversational tone with {emotional_tone.lower()} emotional undertones - Use transition words for flow - Include personal anecdotes or expert experiences - Balance scientific information with practical advice - Write in {pov} person consistently - Maintain {tone.lower()} tone throughout HTML STRUCTURE & TECHNICAL REQUIREMENTS: CRITICAL: Follow these HTML best practices exactly: 1. **Clean HTML Structure:** - Use semantic HTML5 elements:
,
,
- Wrap major content sections in
tags - No placeholder text for images/videos - use HTML comments instead - Clean, professional code structure 2. **Schema Markup:** - Complete FAQPage schema with proper opening/closing divs - Include at least 5-8 FAQ items with full schema markup - Ensure all schema containers are properly closed 3. **Content Organization:** - No inline questions within list items - Separate Q&A content into dedicated paragraphs or FAQ section - Use proper paragraph structure for readability 4. **Media Placeholders:** - Replace "(Include photos here)" with: - Replace "(Embed video)" with: - Use commented HTML examples for future media 5. **Links and References:** - Use real, working links when possible - If using example.com, make it clear it's a placeholder - Include rel="noopener" for external links 6. **Accessibility:** - Include lang="en" in html tag - Prepare alt text suggestions in comments for images - Use semantic heading hierarchy EXAMPLE HTML STRUCTURE TO FOLLOW: ```html

Section Title

Content here...

Subsection

  1. Step one
  2. Step two

Common Question: Answer here...

FAQ Section

Question?

Answer here.

``` IMPORTANT: Generate ONLY the article content with proper HTML structure. Do NOT include any CSS styles, head tags, or full HTML document structure. Return only the article content that will be inserted into an existing page. OUTPUT FORMAT: Provide only the article content with: 1. Meta title and description at the top (as text, not HTML meta tags) 2. Full HTML-formatted article with proper semantic structure (content only) 3. Complete FAQ section with 6-8 questions and proper schema 4. Clean, professional HTML with no placeholder text 5. Commented placeholders for media elements 6. Natural integration of provided internal links Generate the article now, ensuring it follows all HTML best practices and is optimized for 2025 SEO standards. """ return prompt def generate_title_variations(self, main_topic): """Generate title variations using Gemini""" if not self.model: return ["Title generation requires API configuration"] prompt = f""" Generate 5 SEO-optimized title variations for a fermentation article about: {main_topic} Requirements: - 50-60 characters each - Include power words and emotional triggers - Fermentation/gut health focus - Different angles (beginner guide, expert tips, complete guide, etc.) - Optimize for click-through rate Format as a numbered list. """ try: response = self.model.generate_content(prompt) return response.text.split('\n') except Exception as e: return [f"Error generating titles: {str(e)}"] def generate_article(self, api_key, seo_plan, pov, tone, length, internal_links_text, extra_keywords_text, emotional_tone, generate_titles, include_readability): """Main function to generate the SEO article""" # Configure API if not api_key.strip(): return "❌ Error: Please enter your Gemini 1.5 Pro API key", "", "", "", "" success, message = self.configure_gemini(api_key) if not success: return f"❌ {message}", "", "", "", "" if not seo_plan.strip(): return "❌ Error: Please provide your SEO article plan or keyword target", "", "", "", "" try: # Parse inputs internal_links = self.parse_internal_links(internal_links_text) extra_keywords = self.parse_extra_keywords(extra_keywords_text) # Generate main article prompt = self.generate_seo_prompt( seo_plan, pov, tone, length, internal_links, extra_keywords, emotional_tone, generate_titles, include_readability ) response = self.model.generate_content(prompt) article_content = response.text # Generate title variations if requested title_variations = "" if generate_titles: titles = self.generate_title_variations(seo_plan) title_variations = "🎯 **TITLE VARIATIONS:**\n" + "\n".join(titles) + "\n\n" # Calculate readability if requested readability_analysis = "" if include_readability: metrics = self.calculate_readability(article_content) readability_analysis = f""" 📊 **READABILITY ANALYSIS:** - Word Count: {metrics['words']} words - Sentences: {metrics['sentences']} - Flesch Reading Ease: {metrics['flesch_score']}/100 (Higher is easier) - Grade Level: {metrics['grade_level']} (U.S. grade level) """ # Combine all outputs final_output = title_variations + readability_analysis + article_content # Create HTML version for preview - FIXED VERSION with contained CSS html_content = f"""
{final_output.replace(chr(10), '
') if not '

' in final_output else final_output}

""" # Create downloadable HTML file (full document) download_html = f""" Generated SEO Article
{final_output}
""" # Create markdown version markdown_content = final_output # Create downloadable HTML file html_download = base64.b64encode(download_html.encode()).decode() return ( "✅ Article generated successfully!", final_output, html_content, markdown_content, html_download ) except Exception as e: return f"❌ Error generating article: {str(e)}", "", "", "", "" # Initialize the generator generator = FermentationSEOGenerator() # Create Gradio interface def create_interface(): with gr.Blocks(title="Fermentation AI SEO Tool", theme=gr.themes.Soft()) as app: gr.Markdown(""" # 🧬 Fermentation AI SEO Tool – Powered by Gemini 1.5 Pro Generate high-quality, SEO-optimized articles focused on fermentation, gut health, and traditional food preservation. Optimized for 2025 SEO standards with E-A-T, featured snippets, and semantic optimization. """) with gr.Row(): api_key = gr.Textbox( label="Enter Gemini 1.5 Pro API Key", placeholder="Enter your API key here...", type="password", lines=1 ) with gr.Row(): seo_plan = gr.Textbox( label="Paste Your SEO Article Plan or Keyword Target", placeholder="Example: How to ferment vegetables at home for beginners, fermentation guide, lacto-fermentation process", lines=3 ) with gr.Row(): with gr.Column(): pov = gr.Dropdown( choices=["First", "Second", "Third"], value="Second", label="Point of View" ) tone = gr.Dropdown( choices=["Friendly", "Professional", "Quirky"], value="Friendly", label="Blog Tone" ) with gr.Column(): length = gr.Dropdown( choices=["Short", "Standard", "Long Form"], value="Standard", label="Content Length" ) emotional_tone = gr.Dropdown( choices=["Trust", "Curiosity", "Joy"], value="Trust", label="Emotional Tone Injection" ) with gr.Row(): with gr.Column(): internal_links = gr.Textbox( label="Internal Links (keyword:link format, 1 per line)", placeholder="fermented garlic benefits:https://example.com/fermented-garlic\nkombucha brewing:https://example.com/kombucha-guide", lines=4 ) with gr.Column(): extra_keywords = gr.Textbox( label="Extra Keywords (1 per line)", placeholder="lacto-fermentation\nfermented vegetables\nprobiotics\ngut health", lines=4 ) with gr.Row(): generate_titles = gr.Checkbox( label="Generate Title Variations (3–5 options)", value=True ) include_readability = gr.Checkbox( label="Include Readability Analysis (Flesch, Grade Level)", value=True ) generate_btn = gr.Button("🚀 Generate Article", variant="primary", size="lg") with gr.Row(): status = gr.Textbox(label="Status", interactive=False) with gr.Tabs(): with gr.TabItem("📝 Article Output"): article_output = gr.Textbox( label="Generated SEO Article", lines=25, max_lines=50, show_copy_button=True ) with gr.TabItem("🌐 HTML Preview"): html_preview = gr.HTML(label="HTML Preview") html_download = gr.File( label="Download HTML File", visible=False ) download_btn = gr.Button("📥 Download HTML File", variant="secondary") with gr.TabItem("📄 Markdown"): markdown_output = gr.Textbox( label="Markdown Format", lines=20, show_copy_button=True ) # Event handlers def generate_and_process(*args): result = generator.generate_article(*args) status_msg, article, html_content, markdown, html_b64 = result # Create downloadable file if html_b64: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"fermentation_article_{timestamp}.html" html_file = gr.File(value=None, visible=True) return status_msg, article, html_content, markdown, html_file return status_msg, article, html_content, markdown, gr.File(visible=False) def create_download_file(html_content): if html_content: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"fermentation_article_{timestamp}.html" # Create full HTML document for download download_html = f""" Generated SEO Article
{html_content}
""" with open(filename, 'w', encoding='utf-8') as f: f.write(download_html) return gr.File(value=filename, visible=True) return gr.File(visible=False) generate_btn.click( fn=generate_and_process, inputs=[ api_key, seo_plan, pov, tone, length, internal_links, extra_keywords, emotional_tone, generate_titles, include_readability ], outputs=[status, article_output, html_preview, markdown_output, html_download] ) download_btn.click( fn=create_download_file, inputs=[html_preview], outputs=[html_download] ) gr.Markdown(""" --- ### 💡 **Updated for Clean HTML Generation:** - ✅ **Semantic HTML5** - Uses proper `
` tags and structure - ✅ **Complete Schema Markup** - Properly closed FAQ schema with 6-8 questions - ✅ **No Placeholder Text** - Clean HTML comments for media placeholders - ✅ **Accessibility Ready** - Proper lang attributes and semantic structure - ✅ **Professional Code** - No inline Q&A in lists, clean paragraph structure - ✅ **Fixed CSS Issues** - Contained styling that won't affect parent app ### 🎯 **Tips for Best Results:** - Use specific fermentation-related keywords in your SEO plan - Include 2-4 internal links with relevant anchor text (keyword:link format) - Add 5-10 related keywords for semantic SEO enhancement - Longer content typically performs better for competitive keywords - Generated HTML is production-ready with proper schema markup **Powered by Gemini 1.5 Pro API** | Built for Professional Fermentation Content """) return app # Launch the app if __name__ == "__main__": app = create_interface() app.launch( #server_name="0.0.0.0", #server_port=7860, #share=True, #show_error=True )