divanshuthakur111's picture
Update app.py
c903561 verified
import os
import gradio as gr
from dotenv import load_dotenv
from crewai import Agent, Task, Crew
from crewai_tools import ScrapeWebsiteTool, SerperDevTool
# Load environment variables from .env file
# Make sure you have a .env file with your SERPER_API_KEY
load_dotenv()
# --- Main Crew AI Logic Function ---
def run_website_review_crew(website_url: str):
"""
Sets up and runs the CrewAI agents and tasks to create a 27-day action plan for a website.
"""
if not website_url:
yield "Please enter a valid website URL."
return
yield "Crew is assembling... 🚀 Please wait."
# Initialize tools
scrape_tool = ScrapeWebsiteTool()
search_tool = SerperDevTool()
# --- AGENT DEFINITIONS ---
scraper = Agent(
role='Website Content Scraper',
goal=f'Scrape all text, structure, and identify key images from {website_url}',
backstory="An expert web scraper who extracts clean, relevant content and HTML structure, noting any images that seem generic or low-quality.",
verbose=True,
allow_delegation=False,
tools=[scrape_tool]
)
design_analyst = Agent(
role='Website Design & Content Analyst',
goal='Analyze the website’s layout, accessibility, and content quality. Pinpoint specific paragraphs and images that are suboptimal.',
backstory="A UI/UX specialist with a keen eye for content. You identify weaknesses in design, navigation, and writing, and flag specific elements for improvement.",
verbose=True,
allow_delegation=False,
)
content_rewriter = Agent(
role='Expert SEO Content Writer',
goal='Rewrite identified weak paragraphs to be more engaging, clear, and SEO-friendly.',
backstory="A professional copywriter who transforms dull text into compelling, user-centric content that also ranks well on search engines.",
verbose=True,
allow_delegation=False,
)
visual_consultant = Agent(
role='Visual Design Consultant',
goal='Find and suggest high-quality, relevant, and royalty-free replacement images for the website.',
backstory="A creative director who understands brand identity and sources powerful, royalty-free visuals from sites like Unsplash and Pexels to enhance a website's appeal.",
verbose=True,
allow_delegation=False,
tools=[search_tool]
)
project_manager = Agent(
role='Web Improvement Project Manager',
goal='Compile all analyses and suggestions into a structured, actionable 27-day plan.',
backstory="An organized project manager who breaks down complex website improvements into a clear, day-by-day schedule that is easy for a client to follow.",
verbose=True,
allow_delegation=True,
)
# --- TASK DEFINITIONS ---
scrape_task = Task(
description=f'Scrape the main content, HTML structure, and image descriptions from: {website_url}',
expected_output='A clean dump of the site’s content, layout, and a list of key images to be reviewed.',
agent=scraper
)
analyze_task = Task(
description="""Analyze the scraped content. Identify specific weaknesses in:
- UI/UX, navigation, and mobile responsiveness.
- Text content: Find up to 3 paragraphs that are vague, poorly written, or not engaging.
- Visuals: Identify up to 3 images that look generic, low-quality, or irrelevant.
Create a summary of these weak points.""",
expected_output='A detailed report listing design flaws, and the specific text and image elements that need replacement.',
agent=design_analyst,
context=[scrape_task]
)
rewrite_task = Task(
description="""Based on the analysis of weak text, rewrite the identified paragraphs.
For each paragraph, provide both the original and the improved version.""",
expected_output='A document containing side-by-side comparisons of the original, weak paragraphs and the newly rewritten, engaging versions.',
agent=content_rewriter,
context=[analyze_task]
)
image_task = Task(
description="""Based on the analysis of weak images, find high-quality, royalty-free replacements.
For each suggested image, provide a brief description of why it's a better fit and a direct link to a source like Unsplash or Pexels.""",
expected_output='A list of suggested replacement images, each with a justification and a direct URL.',
agent=visual_consultant,
context=[analyze_task]
)
planning_task = Task(
description="""Compile all findings into a single, cohesive 27-day action plan.
- Integrate the UI/UX, navigation, and accessibility suggestions.
- Incorporate the rewritten text, showing the 'Original' and 'Suggested Replacement'.
- Incorporate the new image suggestions with their links.
- Break down all tasks logically over 27 days, giving one small, manageable task per day.
The final output MUST be well-formatted markdown, with a heading for each day (e.g., '### Day 1: [Task Title]').""",
expected_output="A complete, day-by-day website improvement plan in markdown format, ready for the client.",
agent=project_manager,
context=[analyze_task, rewrite_task, image_task]
)
# Assemble and run the crew
website_review_crew = Crew(
agents=[scraper, design_analyst, content_rewriter, visual_consultant, project_manager],
tasks=[scrape_task, analyze_task, rewrite_task, image_task, planning_task],
verbose=True
)
yield "Crew has started the review... 🕵️‍♂️ This may take a few moments."
try:
result = website_review_crew.kickoff()
yield result
except Exception as e:
print(f"An error occurred: {e}")
yield f"An error occurred during the analysis. Please check the console for details. Error: {e}"
# --- Gradio Interface Definition ---
with gr.Blocks(theme=gr.themes.Soft(), title="Website Improvement Planner") as iface:
gr.Markdown(
"""
# 🤖 Website Improvement 27-Day Planner
Enter a URL to receive a comprehensive, day-by-day action plan to improve your website.
The crew will rewrite content, find better images, and suggest structural improvements.
"""
)
with gr.Row():
website_input = gr.Textbox(
label="Website URL",
placeholder="e.g., https://www.example.com",
value="https://www.abhilashiuniversity.ac.in/"
)
analyze_button = gr.Button("🚀 Generate 27-Day Plan", variant="primary")
gr.Markdown("---")
gr.Markdown("## 📊 Your Action Plan")
result_output = gr.Markdown(label="Crew's Report", value="Your detailed plan will appear here...")
# The analyze_button now only updates the text output area
analyze_button.click(
fn=run_website_review_crew,
inputs=[website_input],
outputs=[result_output]
)
if __name__ == '__main__':
iface.launch()