Saqib772 commited on
Commit
7fddf41
Β·
verified Β·
1 Parent(s): 462a413

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +299 -300
app.py CHANGED
@@ -1,300 +1,299 @@
1
- import gradio as gr
2
- from dotenv import load_dotenv
3
- import os
4
- import time
5
- from typing import Dict, Any
6
-
7
- # Load environment variables
8
- load_dotenv()
9
-
10
- # Import crew agents after environment setup
11
- from crewai import Agent, Task, Crew, LLM
12
- from crewai_tools import SerperDevTool, WebsiteSearchTool
13
-
14
- # Initialize tools
15
- search_tool = SerperDevTool()
16
- web_rag_tool = WebsiteSearchTool()
17
-
18
- # Initialize LLM
19
- llm = LLM(
20
- model="gemini/gemini-2.0-flash",
21
- temperature=0.7,
22
- stream=False # Set to False for Gradio compatibility
23
- )
24
-
25
- def create_crew_for_topic(topic: str) -> Crew:
26
- """Create a crew with agents for the given topic"""
27
-
28
- # Research Specialist Agent
29
- research_agent = Agent(
30
- role="Research Specialist",
31
- goal=f"Research interesting facts about the topic: {topic}",
32
- backstory="You are a highly skilled research assistant that can research the web and provide factual data",
33
- llm=llm,
34
- tools=[search_tool],
35
- verbose=False
36
- )
37
-
38
- # Creative Writer Agent
39
- writer_agent = Agent(
40
- role="Creative Writer",
41
- goal="Write a 250 words blog using the research and it must start with a hook, introduction para, body para, conclusion para and end with a call to action",
42
- backstory="You are a highly skilled writer assistant that can write a blog post about the topic",
43
- llm=llm,
44
- verbose=False
45
- )
46
-
47
- # Create tasks
48
- task1 = Task(
49
- description=f"Research interesting 4-5 facts about the topic: {topic}",
50
- expected_output="A bullet point list of 4-5 facts about the topic",
51
- agent=research_agent
52
- )
53
-
54
- task2 = Task(
55
- description=f"Write a 250 words blog using the research on {topic} and must be a casual tone",
56
- expected_output="Blog post",
57
- agent=writer_agent,
58
- context=[task1]
59
- )
60
-
61
- # Create crew
62
- crew = Crew(
63
- agents=[research_agent, writer_agent],
64
- tasks=[task1, task2],
65
- verbose=False
66
- )
67
-
68
- return crew
69
-
70
- def generate_blog(topic: str, progress=gr.Progress()) -> Dict[str, Any]:
71
- """Generate blog content using crew agents"""
72
-
73
- if not topic.strip():
74
- return {
75
- "status": "error",
76
- "message": "Please enter a topic for blog generation."
77
- }
78
-
79
- try:
80
- progress(0.1, desc="Initializing crew agents...")
81
-
82
- # Create crew for the topic
83
- crew = create_crew_for_topic(topic)
84
-
85
- progress(0.3, desc="Researching topic...")
86
-
87
- # Execute the crew tasks
88
- response = crew.kickoff(inputs={"topic": topic})
89
-
90
- progress(0.8, desc="Finalizing blog post...")
91
-
92
- # Simulate some processing time for better UX
93
- time.sleep(0.5)
94
-
95
- progress(1.0, desc="Blog generated successfully!")
96
-
97
- return {
98
- "status": "success",
99
- "topic": topic,
100
- "blog_content": response,
101
- "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
102
- }
103
-
104
- except Exception as e:
105
- return {
106
- "status": "error",
107
- "message": f"An error occurred: {str(e)}"
108
- }
109
-
110
- def format_blog_output(result: Dict[str, Any]) -> str:
111
- """Format the blog output for display"""
112
- if result["status"] == "error":
113
- return f"❌ **Error**: {result['message']}"
114
-
115
- blog_content = result["blog_content"]
116
- topic = result["topic"]
117
- timestamp = result["timestamp"]
118
-
119
- formatted_output = f"""
120
- # πŸ“ Blog Post: {topic}
121
-
122
- **Generated on:** {timestamp}
123
-
124
- ---
125
-
126
- {blog_content}
127
-
128
- ---
129
-
130
- *This blog post was generated using AI-powered research and writing agents.*
131
- """
132
-
133
- return formatted_output
134
-
135
- # Create Gradio interface
136
- with gr.Blocks(
137
- title="Crew Agents - AI Blog Generator",
138
- theme=gr.themes.Soft(),
139
- css="""
140
- .gradio-container {
141
- max-width: 1200px !important;
142
- margin: 0 auto !important;
143
- }
144
- .header {
145
- text-align: center;
146
- padding: 20px;
147
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
148
- color: white;
149
- border-radius: 2px;
150
- margin-bottom: 30px;
151
- }
152
-
153
- .output-section {
154
- background: white !important;
155
- padding: 25px !important;
156
- border-radius: 5px !important;
157
- border: none !important;
158
- outline: none !important;
159
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1) !important;
160
- }
161
- /* Remove all borders from Gradio components */
162
-
163
- .output-section * {
164
- border: none !important;
165
- outline: none !important;
166
- }
167
-
168
- .output-section .gr-box {
169
- border: none !important;
170
- outline: none !important;
171
- }
172
- /* Remove borders from Group components */
173
- .gr-group {
174
- border: none !important;
175
- outline: none !important;
176
- }
177
- /* Remove borders from all form elements */
178
- .gr-form {
179
- border: none !important;
180
- outline: none !important;
181
- }
182
- /* Target the specific border classes */
183
- .border {
184
- border: none !important;
185
- }
186
- .border-2 {
187
- border: none !important;
188
- }
189
- .border-solid {
190
- border: none !important;
191
- }
192
- .border-gray-200 {
193
- border: none !important;
194
- }
195
- /* Remove any remaining borders */
196
- * {
197
- border-color: transparent !important;
198
- }
199
- """
200
- ) as demo:
201
-
202
- # Header
203
- gr.HTML("""
204
- <div class="header">
205
- <h1>πŸ€– Crew Agents - AI Blog Generator</h1>
206
- <p>Powered by CrewAI - Generate well-researched blog posts in seconds!</p>
207
- </div>
208
- """)
209
-
210
- with gr.Row():
211
- with gr.Column(scale=1):
212
- # Input Section
213
- with gr.Group():
214
- gr.Markdown("## 🎯 **Enter Your Blog Topic**")
215
-
216
- topic_input = gr.Textbox(
217
- label="Blog Topic",
218
- placeholder="e.g., How AI is transforming healthcare, The future of renewable energy...",
219
- lines=3,
220
- max_lines=5,
221
- info="Describe what you want to write about. Be specific for better results!"
222
- )
223
-
224
- generate_btn = gr.Button(
225
- "πŸš€ Generate Blog Post",
226
- variant="primary",
227
- size="lg"
228
- )
229
-
230
- # Example topics
231
- gr.Markdown("""
232
- **πŸ’‘ Example Topics:**
233
- - How AI is revolutionizing agriculture
234
- - The impact of climate change on coastal cities
235
- - Future of remote work in 2026
236
- - Sustainable fashion trends
237
- """)
238
-
239
- with gr.Column(scale=2):
240
- # Output Section
241
- with gr.Group():
242
- gr.Markdown("## πŸ“ **Generated Blog Post**")
243
-
244
- output_markdown = gr.Markdown(
245
- value="Enter a topic above and click 'Generate Blog Post' to get started!",
246
- label="Blog Content"
247
- )
248
-
249
- # Status indicator
250
- status_text = gr.Textbox(
251
- label="Status",
252
- value="Ready to generate",
253
- interactive=False
254
- )
255
-
256
- # Footer
257
- gr.HTML("""
258
- <div style="text-align: center; margin-top: 30px; padding: 20px; color: #666;">
259
- <p>Built with ❀️ using <a href="https://github.com/joaomdmoura/crewAI" target="_blank">CrewAI</a> and <a href="https://ai.google.dev/" target="_blank">Google Gemini</a></p>
260
- </div>
261
- """)
262
-
263
- # Event handlers
264
- def on_generate(topic):
265
- if not topic.strip():
266
- return "Please enter a topic for blog generation.", "No topic provided"
267
-
268
- # Update status
269
- yield "Generating blog post...", "Processing..."
270
-
271
- # Generate blog
272
- result = generate_blog(topic)
273
-
274
- if result["status"] == "success":
275
- formatted_blog = format_blog_output(result)
276
- yield formatted_blog, "Blog generated successfully!"
277
- else:
278
- yield f"❌ **Error**: {result['message']}", "Generation failed"
279
-
280
- generate_btn.click(
281
- fn=on_generate,
282
- inputs=[topic_input],
283
- outputs=[output_markdown, status_text]
284
- )
285
-
286
- # Enter key support
287
- topic_input.submit(
288
- fn=on_generate,
289
- inputs=[topic_input],
290
- outputs=[output_markdown, status_text]
291
- )
292
-
293
- # Launch the app
294
- if __name__ == "__main__":
295
- demo.launch(
296
- server_name="127.0.0.1",
297
- server_port=7860,
298
- share=False,
299
- show_error=True
300
- )
 
1
+ import gradio as gr
2
+ from dotenv import load_dotenv
3
+ import os
4
+ import time
5
+ from typing import Dict, Any
6
+
7
+ # Load environment variables
8
+ load_dotenv()
9
+
10
+ # Import crew agents after environment setup
11
+ from crewai import Agent, Task, Crew, LLM
12
+ from crewai_tools import SerperDevTool
13
+
14
+ # Initialize tools
15
+ search_tool = SerperDevTool()
16
+
17
+ # Initialize LLM
18
+ llm = LLM(
19
+ model="gemini/gemini-2.0-flash",
20
+ temperature=0.7,
21
+ stream=False # Set to False for Gradio compatibility
22
+ )
23
+
24
+ def create_crew_for_topic(topic: str) -> Crew:
25
+ """Create a crew with agents for the given topic"""
26
+
27
+ # Research Specialist Agent
28
+ research_agent = Agent(
29
+ role="Research Specialist",
30
+ goal=f"Research interesting facts about the topic: {topic}",
31
+ backstory="You are a highly skilled research assistant that can research the web and provide factual data",
32
+ llm=llm,
33
+ tools=[search_tool],
34
+ verbose=False
35
+ )
36
+
37
+ # Creative Writer Agent
38
+ writer_agent = Agent(
39
+ role="Creative Writer",
40
+ goal="Write a 250 words blog using the research and it must start with a hook, introduction para, body para, conclusion para and end with a call to action",
41
+ backstory="You are a highly skilled writer assistant that can write a blog post about the topic",
42
+ llm=llm,
43
+ verbose=False
44
+ )
45
+
46
+ # Create tasks
47
+ task1 = Task(
48
+ description=f"Research interesting 4-5 facts about the topic: {topic}",
49
+ expected_output="A bullet point list of 4-5 facts about the topic",
50
+ agent=research_agent
51
+ )
52
+
53
+ task2 = Task(
54
+ description=f"Write a 250 words blog using the research on {topic} and must be a casual tone",
55
+ expected_output="Blog post",
56
+ agent=writer_agent,
57
+ context=[task1]
58
+ )
59
+
60
+ # Create crew
61
+ crew = Crew(
62
+ agents=[research_agent, writer_agent],
63
+ tasks=[task1, task2],
64
+ verbose=False
65
+ )
66
+
67
+ return crew
68
+
69
+ def generate_blog(topic: str, progress=gr.Progress()) -> Dict[str, Any]:
70
+ """Generate blog content using crew agents"""
71
+
72
+ if not topic.strip():
73
+ return {
74
+ "status": "error",
75
+ "message": "Please enter a topic for blog generation."
76
+ }
77
+
78
+ try:
79
+ progress(0.1, desc="Initializing crew agents...")
80
+
81
+ # Create crew for the topic
82
+ crew = create_crew_for_topic(topic)
83
+
84
+ progress(0.3, desc="Researching topic...")
85
+
86
+ # Execute the crew tasks
87
+ response = crew.kickoff(inputs={"topic": topic})
88
+
89
+ progress(0.8, desc="Finalizing blog post...")
90
+
91
+ # Simulate some processing time for better UX
92
+ time.sleep(0.5)
93
+
94
+ progress(1.0, desc="Blog generated successfully!")
95
+
96
+ return {
97
+ "status": "success",
98
+ "topic": topic,
99
+ "blog_content": response,
100
+ "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
101
+ }
102
+
103
+ except Exception as e:
104
+ return {
105
+ "status": "error",
106
+ "message": f"An error occurred: {str(e)}"
107
+ }
108
+
109
+ def format_blog_output(result: Dict[str, Any]) -> str:
110
+ """Format the blog output for display"""
111
+ if result["status"] == "error":
112
+ return f"❌ **Error**: {result['message']}"
113
+
114
+ blog_content = result["blog_content"]
115
+ topic = result["topic"]
116
+ timestamp = result["timestamp"]
117
+
118
+ formatted_output = f"""
119
+ # πŸ“ Blog Post: {topic}
120
+
121
+ **Generated on:** {timestamp}
122
+
123
+ ---
124
+
125
+ {blog_content}
126
+
127
+ ---
128
+
129
+ *This blog post was generated using AI-powered research and writing agents.*
130
+ """
131
+
132
+ return formatted_output
133
+
134
+ # Create Gradio interface
135
+ with gr.Blocks(
136
+ title="Crew Agents - AI Blog Generator",
137
+ theme=gr.themes.Soft(),
138
+ css="""
139
+ .gradio-container {
140
+ max-width: 1200px !important;
141
+ margin: 0 auto !important;
142
+ }
143
+ .header {
144
+ text-align: center;
145
+ padding: 20px;
146
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
147
+ color: white;
148
+ border-radius: 2px;
149
+ margin-bottom: 30px;
150
+ }
151
+
152
+ .output-section {
153
+ background: white !important;
154
+ padding: 25px !important;
155
+ border-radius: 5px !important;
156
+ border: none !important;
157
+ outline: none !important;
158
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1) !important;
159
+ }
160
+ /* Remove all borders from Gradio components */
161
+
162
+ .output-section * {
163
+ border: none !important;
164
+ outline: none !important;
165
+ }
166
+
167
+ .output-section .gr-box {
168
+ border: none !important;
169
+ outline: none !important;
170
+ }
171
+ /* Remove borders from Group components */
172
+ .gr-group {
173
+ border: none !important;
174
+ outline: none !important;
175
+ }
176
+ /* Remove borders from all form elements */
177
+ .gr-form {
178
+ border: none !important;
179
+ outline: none !important;
180
+ }
181
+ /* Target the specific border classes */
182
+ .border {
183
+ border: none !important;
184
+ }
185
+ .border-2 {
186
+ border: none !important;
187
+ }
188
+ .border-solid {
189
+ border: none !important;
190
+ }
191
+ .border-gray-200 {
192
+ border: none !important;
193
+ }
194
+ /* Remove any remaining borders */
195
+ * {
196
+ border-color: transparent !important;
197
+ }
198
+ """
199
+ ) as demo:
200
+
201
+ # Header
202
+ gr.HTML("""
203
+ <div class="header">
204
+ <h1>πŸ€– Crew Agents - AI Blog Generator</h1>
205
+ <p>Powered by CrewAI - Generate well-researched blog posts in seconds!</p>
206
+ </div>
207
+ """)
208
+
209
+ with gr.Row():
210
+ with gr.Column(scale=1):
211
+ # Input Section
212
+ with gr.Group():
213
+ gr.Markdown("## 🎯 **Enter Your Blog Topic**")
214
+
215
+ topic_input = gr.Textbox(
216
+ label="Blog Topic",
217
+ placeholder="e.g., How AI is transforming healthcare, The future of renewable energy...",
218
+ lines=3,
219
+ max_lines=5,
220
+ info="Describe what you want to write about. Be specific for better results!"
221
+ )
222
+
223
+ generate_btn = gr.Button(
224
+ "πŸš€ Generate Blog Post",
225
+ variant="primary",
226
+ size="lg"
227
+ )
228
+
229
+ # Example topics
230
+ gr.Markdown("""
231
+ **πŸ’‘ Example Topics:**
232
+ - How AI is revolutionizing agriculture
233
+ - The impact of climate change on coastal cities
234
+ - Future of remote work in 2026
235
+ - Sustainable fashion trends
236
+ """)
237
+
238
+ with gr.Column(scale=2):
239
+ # Output Section
240
+ with gr.Group():
241
+ gr.Markdown("## πŸ“ **Generated Blog Post**")
242
+
243
+ output_markdown = gr.Markdown(
244
+ value="Enter a topic above and click 'Generate Blog Post' to get started!",
245
+ label="Blog Content"
246
+ )
247
+
248
+ # Status indicator
249
+ status_text = gr.Textbox(
250
+ label="Status",
251
+ value="Ready to generate",
252
+ interactive=False
253
+ )
254
+
255
+ # Footer
256
+ gr.HTML("""
257
+ <div style="text-align: center; margin-top: 30px; padding: 20px; color: #666;">
258
+ <p>Built with ❀️ using <a href="https://github.com/joaomdmoura/crewAI" target="_blank">CrewAI</a> and <a href="https://ai.google.dev/" target="_blank">Google Gemini</a></p>
259
+ </div>
260
+ """)
261
+
262
+ # Event handlers
263
+ def on_generate(topic):
264
+ if not topic.strip():
265
+ return "Please enter a topic for blog generation.", "No topic provided"
266
+
267
+ # Update status
268
+ yield "Generating blog post...", "Processing..."
269
+
270
+ # Generate blog
271
+ result = generate_blog(topic)
272
+
273
+ if result["status"] == "success":
274
+ formatted_blog = format_blog_output(result)
275
+ yield formatted_blog, "Blog generated successfully!"
276
+ else:
277
+ yield f"❌ **Error**: {result['message']}", "Generation failed"
278
+
279
+ generate_btn.click(
280
+ fn=on_generate,
281
+ inputs=[topic_input],
282
+ outputs=[output_markdown, status_text]
283
+ )
284
+
285
+ # Enter key support
286
+ topic_input.submit(
287
+ fn=on_generate,
288
+ inputs=[topic_input],
289
+ outputs=[output_markdown, status_text]
290
+ )
291
+
292
+ # Launch the app
293
+ if __name__ == "__main__":
294
+ demo.launch(
295
+ server_name="127.0.0.1",
296
+ server_port=7860,
297
+ share=False,
298
+ show_error=True
299
+ )