Akshayram1 commited on
Commit
ce72271
·
verified ·
1 Parent(s): 31c2376

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -95
app.py CHANGED
@@ -3,9 +3,7 @@ from crewai import Agent, Task, Crew, Process
3
  from crewai_tools import WebsiteSearchTool
4
  from dotenv import load_dotenv
5
  import os
6
- from fpdf import FPDF
7
- from io import BytesIO
8
- import textwrap
9
 
10
  # Load environment variables
11
  load_dotenv()
@@ -17,6 +15,14 @@ st.sidebar.header("Input")
17
  # OpenAI API key input
18
  user_api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password")
19
  news_link = st.sidebar.text_input("Enter News Link", "")
 
 
 
 
 
 
 
 
20
  generate_blog = st.sidebar.button("Generate Blog")
21
 
22
  if generate_blog:
@@ -32,8 +38,8 @@ if generate_blog:
32
 
33
  # Create agents
34
  blog_researcher = Agent(
35
- role='AI Blog Researcher from News Website',
36
- goal='Get the relevant latest AI related news from News Website',
37
  verbose=True,
38
  memory=True,
39
  backstory=("Expert in understanding videos in AI, Data Science, Machine Learning, and GEN AI."),
@@ -42,8 +48,8 @@ if generate_blog:
42
  )
43
 
44
  blog_writer = Agent(
45
- role='Blog Writer',
46
- goal='Narrate compelling tech stories about the News Article and add the reference links at the end of the blog.',
47
  verbose=True,
48
  memory=True,
49
  backstory=(
@@ -57,62 +63,62 @@ if generate_blog:
57
  # Define tasks
58
  research_task = Task(
59
  description=(
60
- "Research Task: "
61
- "1. Visit the provided news link and analyze the content thoroughly\n"
62
- "2. Extract key information about the AI-related news or development\n"
63
- "3. Identify main points, technological aspects, and potential impact\n"
64
- "4. Gather any relevant background information or context\n"
65
- "5. Note any quotes, statistics, or specific technical details"
66
  ),
67
- expected_output=(
68
- "A detailed research report containing:\n"
69
- "- Main story/development summary\n"
70
- "- Technical aspects and innovations\n"
71
- "- Impact and implications\n"
72
- "- Supporting facts and context\n"
73
- "- Notable quotes or statistics"
74
- ),
75
- agent=blog_researcher
76
  )
77
 
78
  write_task = Task(
79
  description=(
80
- "Writing Task:\n"
81
- "1. Use the research findings to craft an engaging blog post\n"
82
- "2. Structure the content with clear introduction, body, and conclusion\n"
83
- "3. Explain technical concepts in an accessible manner\n"
84
- "4. Include relevant examples and real-world applications\n"
85
- "5. Add reference links at the end"
86
  ),
87
- expected_output=(
88
- "A well-structured blog post that includes:\n"
89
- "- Engaging headline and introduction\n"
90
- "- Clear explanation of the AI development\n"
91
- "- Technical details explained simply\n"
92
- "- Impact and future implications\n"
93
- "- Reference links"
94
- ),
95
- agent=blog_writer
96
  )
97
 
98
- # Create crew - Fixed verbose parameter to be boolean
99
  crew = Crew(
100
  agents=[blog_researcher, blog_writer],
101
  tasks=[research_task, write_task],
102
  process=Process.sequential,
103
- verbose=True # Changed from 2 to True
 
 
 
104
  )
105
 
 
106
  try:
107
- # Kickoff the process with the news link as input
108
- result = crew.kickoff(inputs={'topic': news_link})
109
-
110
- # Extract blog content from the result
111
- if hasattr(result, 'tasks_output'):
112
- blog_content = result.tasks_output[-1].raw # Get the last task's output
113
- else:
114
- # If tasks_output is not available, try to get the raw result
115
- blog_content = str(result)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
  # Display the blog content
118
  st.subheader("Generated Blog")
@@ -120,66 +126,34 @@ if generate_blog:
120
 
121
  # Actions to save or reject the blog
122
  st.subheader("Actions")
123
- save_blog = st.button("Save Blog as PDF")
124
  reject_blog = st.button("Reject Blog")
125
 
126
  if save_blog:
127
  try:
128
- # Create PDF with proper text wrapping and formatting
129
- pdf = FPDF()
130
- pdf.add_page()
131
- pdf.set_auto_page_break(auto=True, margin=15)
132
-
133
- # Add title
134
- pdf.set_font("Arial", "B", 16)
135
- pdf.cell(0, 10, "Generated Blog", ln=True, align='C')
136
- pdf.ln(10)
137
-
138
- # Add content with proper formatting
139
- pdf.set_font("Arial", size=12)
140
-
141
- # Process and wrap text
142
- effective_page_width = pdf.w - 2 * pdf.l_margin
143
-
144
- # Split content into paragraphs
145
- paragraphs = blog_content.split('\n')
146
-
147
- for paragraph in paragraphs:
148
- if paragraph.strip(): # Only process non-empty paragraphs
149
- # Wrap text to fit page width
150
- wrapped_text = textwrap.fill(paragraph, width=95)
151
-
152
- # Split wrapped text into lines and write them
153
- lines = wrapped_text.split('\n')
154
- for line in lines:
155
- pdf.multi_cell(0, 10, line)
156
- pdf.ln(5) # Add small space between paragraphs
157
-
158
- # Generate PDF bytes
159
- pdf_buffer = BytesIO()
160
- pdf.output(pdf_buffer)
161
- pdf_buffer.seek(0)
162
-
163
- # Create download button
164
  st.download_button(
165
- label="Download Blog as PDF",
166
- data=pdf_buffer,
167
- file_name="generated_blog.pdf",
168
- mime="application/pdf"
169
  )
170
- st.success("Blog saved as PDF and ready for download!")
171
-
172
  except Exception as e:
173
- st.error(f"Failed to save blog as PDF: {str(e)}")
174
- st.error("PDF Generation Error Details:", exc_info=True)
175
 
176
  if reject_blog:
177
  st.warning("Blog rejected. No file was saved.")
178
 
179
  except Exception as e:
180
- st.error(f"An error occurred during the process: {str(e)}")
181
 
182
  else:
183
  st.error("Please enter a valid news link.")
184
  else:
185
- st.error("Please provide your OpenAI API Key.")
 
3
  from crewai_tools import WebsiteSearchTool
4
  from dotenv import load_dotenv
5
  import os
6
+ from io import BytesIO # To handle in-memory files
 
 
7
 
8
  # Load environment variables
9
  load_dotenv()
 
15
  # OpenAI API key input
16
  user_api_key = st.sidebar.text_input("Enter your OpenAI API Key", type="password")
17
  news_link = st.sidebar.text_input("Enter News Link", "")
18
+
19
+ # User inputs for agent configurations
20
+ st.sidebar.subheader("Configure Agents")
21
+ blog_researcher_role = st.sidebar.text_input("Researcher Role", "AI Blog Researcher from News Website")
22
+ blog_researcher_goal = st.sidebar.text_area("Researcher Goal", "Get the relevant latest AI related news from News Website")
23
+ blog_writer_role = st.sidebar.text_input("Writer Role", "Blog Writer")
24
+ blog_writer_goal = st.sidebar.text_area("Writer Goal", "Narrate compelling tech stories about the News Article and add the reference links at the end of the blog.")
25
+
26
  generate_blog = st.sidebar.button("Generate Blog")
27
 
28
  if generate_blog:
 
38
 
39
  # Create agents
40
  blog_researcher = Agent(
41
+ role=blog_researcher_role,
42
+ goal=blog_researcher_goal,
43
  verbose=True,
44
  memory=True,
45
  backstory=("Expert in understanding videos in AI, Data Science, Machine Learning, and GEN AI."),
 
48
  )
49
 
50
  blog_writer = Agent(
51
+ role=blog_writer_role,
52
+ goal=blog_writer_goal,
53
  verbose=True,
54
  memory=True,
55
  backstory=(
 
63
  # Define tasks
64
  research_task = Task(
65
  description=(
66
+ "Identify the News Article and get detailed information about the News from the website."
 
 
 
 
 
67
  ),
68
+ expected_output='A comprehensive 3-paragraph-long report based on the {topic} of News.',
69
+ tools=[web_tool],
70
+ agent=blog_researcher,
 
 
 
 
 
 
71
  )
72
 
73
  write_task = Task(
74
  description=(
75
+ "Get the info from the News Website on the topic {topic}."
 
 
 
 
 
76
  ),
77
+ expected_output='Summarize the info from the News website on the topic {topic} and create the content for the blog.',
78
+ tools=[web_tool],
79
+ agent=blog_writer,
80
+ async_execution=False,
81
+ output_file="" # Provide an empty string or valid file path
 
 
 
 
82
  )
83
 
84
+ # Create crew
85
  crew = Crew(
86
  agents=[blog_researcher, blog_writer],
87
  tasks=[research_task, write_task],
88
  process=Process.sequential,
89
+ memory=True,
90
+ cache=True,
91
+ max_rpm=100,
92
+ share_crew=True
93
  )
94
 
95
+ # Kickoff the process and fetch the result
96
  try:
97
+ with st.spinner("Processing tasks..."):
98
+ result = crew.kickoff(inputs={'topic': news_link})
99
+
100
+ # Inspect result attributes for debugging
101
+ st.subheader("Result Attributes")
102
+ st.write(dir(result))
103
+
104
+ # Access task outputs
105
+ try:
106
+ task_outputs = result.tasks_output
107
+ except AttributeError:
108
+ st.error("The result object does not have 'tasks_output'.")
109
+ task_outputs = []
110
+
111
+ # Display task outputs
112
+ st.subheader("Task Outputs")
113
+ for idx, task_output in enumerate(task_outputs):
114
+ st.write(f"Task {idx + 1}:")
115
+ st.json(task_output)
116
+
117
+ # Extract blog content
118
+ try:
119
+ blog_content = task_outputs[1].raw
120
+ except (IndexError, AttributeError):
121
+ blog_content = "Unable to fetch blog content from the task outputs."
122
 
123
  # Display the blog content
124
  st.subheader("Generated Blog")
 
126
 
127
  # Actions to save or reject the blog
128
  st.subheader("Actions")
129
+ save_blog = st.button("Save Blog as Markdown")
130
  reject_blog = st.button("Reject Blog")
131
 
132
  if save_blog:
133
  try:
134
+ # Save Markdown content in-memory
135
+ markdown_buffer = BytesIO()
136
+ markdown_buffer.write(blog_content.encode('utf-8'))
137
+ markdown_buffer.seek(0)
138
+
139
+ # Provide download button
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  st.download_button(
141
+ label="Download Blog as Markdown",
142
+ data=markdown_buffer,
143
+ file_name="generated_blog.md",
144
+ mime="text/markdown"
145
  )
146
+ st.success("Blog saved as Markdown and ready for download!")
 
147
  except Exception as e:
148
+ st.error(f"Failed to save blog as Markdown: {e}")
 
149
 
150
  if reject_blog:
151
  st.warning("Blog rejected. No file was saved.")
152
 
153
  except Exception as e:
154
+ st.error(f"An error occurred during the process: {e}")
155
 
156
  else:
157
  st.error("Please enter a valid news link.")
158
  else:
159
+ st.error("Please provide your OpenAI API Key.")