mroccuper commited on
Commit
433de95
·
verified ·
1 Parent(s): 1cb5bd5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +223 -0
app.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import google.generativeai as genai
3
+ import os
4
+ from dotenv import load_dotenv
5
+ import time
6
+
7
+ # Load environment variables from .env file if it exists
8
+ load_dotenv()
9
+
10
+ # Function to generate SEO plan with proper error handling
11
+ def generate_seo_plan(topic, api_key, temperature=0.7, max_tokens=4000):
12
+ # Input validation
13
+ if not topic.strip():
14
+ return "⚠️ Please enter a fermentation topic to generate an SEO plan."
15
+
16
+ if not api_key.strip():
17
+ return "⚠️ Please provide your Gemini API key."
18
+
19
+ try:
20
+ # Configure Gemini with the provided API key
21
+ genai.configure(api_key=api_key)
22
+
23
+ # Initialize the model
24
+ model = genai.GenerativeModel(
25
+ "gemini-1.5-pro",
26
+ generation_config={
27
+ "temperature": float(temperature),
28
+ "max_output_tokens": max_tokens,
29
+ "top_p": 0.95
30
+ }
31
+ )
32
+
33
+ # Build the prompt
34
+ prompt = build_prompt(topic)
35
+
36
+ # Generate response
37
+ response = model.generate_content(prompt)
38
+
39
+ # Return formatted response
40
+ return response.text
41
+
42
+ except Exception as e:
43
+ error_message = str(e)
44
+ if "API key not valid" in error_message or "authentication" in error_message.lower():
45
+ return "⚠️ API Key Error: The provided Gemini API key appears to be invalid. Please check your key and try again."
46
+ elif "quota" in error_message.lower():
47
+ return "⚠️ Quota Exceeded: Your Gemini API quota has been exceeded. Please check your Google AI Studio dashboard."
48
+ else:
49
+ return f"⚠️ Error: {error_message}"
50
+
51
+ # Build enhanced SEO prompt for fermentation blog
52
+ def build_prompt(topic):
53
+ return f"""
54
+ 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.
55
+
56
+ For the specific topic: '{topic}'
57
+
58
+ 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.
59
+
60
+ I require the following, formatted in clean markdown:
61
+
62
+ 1. **Strategic Keyword Analysis:**
63
+ * **Primary Target Keyword:**
64
+ * **Secondary Keywords:** 2-3 closely related, high-intent keywords.
65
+ * **Long-Tail Keywords & User Questions:** 5-7 specific user-searched phrases.
66
+ * **Semantic/LSI Keywords:** 5-7 contextually related terms.
67
+ * **Search Intent Analysis:** (Informational, Commercial, etc.)
68
+
69
+ 2. **Competitive Landscape Overview (Top 3-5 Competitors):**
70
+ * For each:
71
+ * URL
72
+ * Strengths
73
+ * Weaknesses
74
+ * Content angle/hook
75
+
76
+ 3. **Content Gaps & Unique Value Proposition:**
77
+ * Missing topics or angles
78
+ * Unique insights or differentiators for *my* blog
79
+
80
+ 4. **Optimized Blog Post Outline:**
81
+ * **H1 Title:**
82
+ * **Meta Description:** (under 160 characters)
83
+ * **Full H2/H3 outline:**
84
+ * **Suggested Visuals:** Where applicable
85
+
86
+ 5. **User-Focused FAQ Section:** 3–5 related to '{topic}'
87
+
88
+ 6. **Internal & External Linking Plan:**
89
+ * **Internal:** 2-3 relevant articles with anchor suggestions
90
+ * **External:** 1-2 reputable sources (.edu, .org, studies)
91
+
92
+ 7. **E-E-A-T Enhancements:**
93
+ * 1-2 ways to show experience, trust, and authority in the content
94
+ """
95
+
96
+ # Save API key to user's preferences
97
+ def save_api_key(api_key):
98
+ if api_key.strip():
99
+ with open(".env", "w") as f:
100
+ f.write(f"GEMINI_API_KEY={api_key}")
101
+ return "✅ API key saved successfully!"
102
+ return "⚠️ Please enter an API key to save"
103
+
104
+ # Function to clear outputs
105
+ def clear_outputs():
106
+ return "", gr.update(value="")
107
+
108
+ # Define theme for better visual experience
109
+ custom_theme = gr.themes.Soft(
110
+ primary_hue="green",
111
+ secondary_hue="emerald",
112
+ ).set(
113
+ body_text_color="#333333",
114
+ block_title_text_weight="600",
115
+ button_primary_background_fill="linear-gradient(90deg, #84cc16 0%, #22c55e 100%)",
116
+ button_primary_background_fill_hover="linear-gradient(90deg, #22c55e 0%, #84cc16 100%)",
117
+ button_primary_text_color="white",
118
+ block_label_text_size="0.9rem",
119
+ block_title_text_size="1.2rem"
120
+ )
121
+
122
+ # Main Gradio app
123
+ with gr.Blocks(title="Fermentation SEO Assistant", theme=custom_theme) as app:
124
+ # Header
125
+ gr.Markdown("""
126
+ # 🌱 Fermentation SEO Content Planner
127
+
128
+ Generate comprehensive SEO plans for your fermentation blog posts using Google's Gemini 1.5 Pro.
129
+ """)
130
+
131
+ # API Key & Configuration Section
132
+ with gr.Accordion("API Key & Settings", open=False):
133
+ with gr.Row():
134
+ api_key_input = gr.Textbox(
135
+ label="Gemini API Key",
136
+ placeholder="Enter your Google Gemini API key",
137
+ value=os.getenv("GEMINI_API_KEY", ""),
138
+ type="password"
139
+ )
140
+ save_btn = gr.Button("💾 Save Key")
141
+
142
+ with gr.Row():
143
+ temperature = gr.Slider(
144
+ minimum=0.0,
145
+ maximum=1.0,
146
+ value=0.7,
147
+ step=0.1,
148
+ label="Temperature (Creativity)",
149
+ info="Higher values = more creative, Lower values = more focused"
150
+ )
151
+ max_tokens = gr.Slider(
152
+ minimum=1000,
153
+ maximum=8000,
154
+ value=4000,
155
+ step=500,
156
+ label="Max Output Length",
157
+ info="Maximum number of tokens in the response"
158
+ )
159
+
160
+ save_btn.click(fn=save_api_key, inputs=api_key_input, outputs=gr.Textbox(label="Status"))
161
+
162
+ # Main content
163
+ with gr.Row():
164
+ with gr.Column(scale=1):
165
+ # Input section
166
+ topic_input = gr.Textbox(
167
+ label="🌶️ Your Fermentation Topic",
168
+ placeholder="e.g., How to Make Kimchi at Home",
169
+ lines=2
170
+ )
171
+
172
+ with gr.Row():
173
+ generate_btn = gr.Button("✨ Generate SEO Plan", variant="primary")
174
+ clear_btn = gr.Button("🔄 Clear", variant="secondary")
175
+
176
+ # Example topics for quick selection
177
+ gr.Examples(
178
+ examples=[
179
+ "Beginner's Guide to Fermenting Vegetables",
180
+ "How to Make Kombucha at Home",
181
+ "The Health Benefits of Fermented Foods",
182
+ "Wild Fermentation: Using Natural Yeasts and Bacteria",
183
+ "Troubleshooting Common Fermentation Problems"
184
+ ],
185
+ inputs=topic_input,
186
+ label="Example Topics"
187
+ )
188
+
189
+ with gr.Column(scale=2):
190
+ # Output section with a visually appealing container
191
+ with gr.Group():
192
+ output_header = gr.Markdown("### Your SEO Plan Will Appear Here")
193
+ seo_output = gr.Markdown()
194
+
195
+ # Button actions
196
+ generate_btn.click(
197
+ fn=generate_seo_plan,
198
+ inputs=[topic_input, api_key_input, temperature, max_tokens],
199
+ outputs=seo_output,
200
+ api_name="generate"
201
+ )
202
+
203
+ clear_btn.click(
204
+ fn=clear_outputs,
205
+ inputs=None,
206
+ outputs=[topic_input, seo_output]
207
+ )
208
+
209
+ # Footer
210
+ gr.Markdown("""
211
+ ---
212
+ ### 📘 How to Use
213
+ 1. Enter your Gemini API key in the settings section (get one from [Google AI Studio](https://aistudio.google.com/))
214
+ 2. Type in your fermentation topic or select from the examples
215
+ 3. Click "Generate SEO Plan" and watch the magic happen!
216
+
217
+ ### 🔑 API Key Security Note
218
+ Your API key is stored locally in a .env file and is never shared with any servers except Google's API services.
219
+ """)
220
+
221
+ # Launch the app
222
+ if __name__ == "__main__":
223
+ app.launch(share=True)