Spaces:
Sleeping
Sleeping
Initial commit with full functionality extend app req tools
Browse filesFiles changed (3)
- Gradio_UI.py+106-116
- app.py+9-26
- requirements.txt+2-16
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157# Gradio_UI.pyimport gradio as grfrom smolagents import CodeAgentfrom typing import Optional, List, Tupleimport loggingfrom bs4 import BeautifulSoupimport requestsimport jsonlogger = logging.getLogger(__name__)class GradioUI:def __init__(self, agent: CodeAgent):self.agent = agentdef fetch_content(self, url: str) -> str:"""Fetch content from URL."""try:response = requests.get(url)response.raise_for_status()soup = BeautifulSoup(response.text, 'html.parser')return soup.get_text()except Exception as e:logger.error(f"Error fetching URL: {str(e)}")return f"Error fetching content: {str(e)}"def analyze_content(self, content: str, analysis_types: List[str]) -> dict:"""Analyze the content based on selected analysis types."""results = {'clean_text': content[:1000] + '...' if len(content) > 1000 else content,'summary': '','sentiment': '','topics': ''}try:if 'summarize' in analysis_types:results['summary'] = self.agent.run(f"Summarize this text: {content[:2000]}")if 'sentiment' in analysis_types:results['sentiment'] = self.agent.run(f"Analyze the sentiment of this text: {content[:2000]}")if 'topics' in analysis_types:results['topics'] = self.agent.run(f"Identify the main topics in this text: {content[:2000]}")except Exception as e:logger.error(f"Error in analysis: {str(e)}")return {'error': str(e),'clean_text': 'Analysis failed','summary': '','sentiment': '','topics': ''}return resultsdef process_url(self, url: str, analysis_types: List[str]) -> Tuple[str, str, str, str]:"""Process URL and return analysis results."""try:# Fetch contentcontent = self.fetch_content(url)# Analyze contentresults = self.analyze_content(content, analysis_types)# Return results for each tabreturn (results.get('clean_text', ''),results.get('summary', ''),results.get('sentiment', ''),results.get('topics', ''))except Exception as e:error_msg = f"Error: {str(e)}"return error_msg, error_msg, error_msg, error_msgdef launch(self,server_name: Optional[str] = None,server_port: Optional[int] = None,share: bool = False):"""Launch the Gradio interface."""with gr.Blocks(title="Smart Web Analyzer Plus") as demo:# Headergr.Markdown("# 🌐 Smart Web Analyzer Plus")gr.Markdown("Analyze web content using AI to extract summaries, determine sentiment, and identify topics.")# Input sectionwith gr.Row():url_input = gr.Textbox(label="Enter URL",placeholder="https://example.com",scale=3)analysis_types = gr.CheckboxGroup(choices=["summarize", "sentiment", "topics"],value=["summarize"],label="Analysis Types",scale=2)analyze_btn = gr.Button("Analyze",variant="primary",scale=1)# Progress indicatorprogress = gr.Markdown(visible=False)# Results section - using a single Tabs componentwith gr.Tabs() as output_tabs:with gr.Tab("Clean Text", id="clean_text"):clean_text_output = gr.Markdown()with gr.Tab("Summary", id="summary"):summary_output = gr.Markdown()with gr.Tab("Sentiment", id="sentiment"):sentiment_output = gr.Markdown()with gr.Tab("Topics", id="topics"):topics_output = gr.Markdown()# Examplesgr.Examples(examples=[["https://www.bbc.com/news/technology-67881954", ["summarize", "sentiment"]],["https://arxiv.org/html/2312.17296v1", ["topics", "summarize"]]],inputs=[url_input, analysis_types])# Event handlersdef show_progress():return gr.update(value="⏳ Analysis in progress...", visible=True)def hide_progress():return gr.update(value="", visible=False)# Connect the button click eventanalyze_btn.click(fn=show_progress,outputs=progress).then(fn=self.process_url,inputs=[url_input, analysis_types],outputs=[clean_text_output, summary_output, sentiment_output, topics_output]).then(fn=hide_progress,outputs=progress)# Launch the interfacedemo.launch(server_name=server_name,server_port=server_port,share=share,debug=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147# Gradio_UI.pyimport gradio as grimport requestsfrom bs4 import BeautifulSoupimport loggingfrom typing import List, Tuplelogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)class WebAnalyzer:def __init__(self, agent):self.agent = agentdef fetch_webpage(self, url: str) -> str:"""Fetch and extract text content from a webpage."""try:response = requests.get(url, timeout=10)response.raise_for_status()soup = BeautifulSoup(response.text, 'html.parser')# Remove script and style elementsfor script in soup(["script", "style"]):script.decompose()text = soup.get_text(separator='\n')# Clean up whitespacelines = (line.strip() for line in text.splitlines())text = '\n'.join(line for line in lines if line)return textexcept Exception as e:logger.error(f"Error fetching webpage: {e}")return f"Error: Failed to fetch webpage - {str(e)}"def analyze_content(self, url: str, analysis_types: List[str]) -> Tuple[str, str, str, str]:"""Analyze webpage content based on selected analysis types."""try:# Fetch contentcontent = self.fetch_webpage(url)if content.startswith("Error:"):return content, "", "", ""# Initialize resultsclean_text = content[:2000] + "..." if len(content) > 2000 else contentsummary = ""sentiment = ""topics = ""# Perform selected analysesif "summarize" in analysis_types:summary = self.agent.run(f"Please summarize this text concisely: {clean_text}")if "sentiment" in analysis_types:sentiment = self.agent.run(f"Analyze the sentiment of this text: {clean_text}")if "topics" in analysis_types:topics = self.agent.run(f"Identify and list the main topics in this text: {clean_text}")return clean_text, summary, sentiment, topicsexcept Exception as e:error_msg = f"Error during analysis: {str(e)}"logger.error(error_msg)return error_msg, "", "", ""class GradioUI:def __init__(self, agent):self.analyzer = WebAnalyzer(agent)def create_interface(self):"""Create the Gradio interface."""# Create interface componentsurl_input = gr.Textbox(label="Enter URL",placeholder="https://example.com")analysis_types = gr.CheckboxGroup(choices=["summarize", "sentiment", "topics"],value=["summarize"],label="Analysis Types")# Create output componentswith gr.Blocks() as demo:gr.Markdown("# Smart Web Analyzer Plus")gr.Markdown("Analyze web content using AI to extract summaries, determine sentiment, and identify topics.")with gr.Row():with gr.Column(scale=4):url_input.render()with gr.Column(scale=2):analysis_types.render()with gr.Column(scale=1):analyze_button = gr.Button("Analyze", variant="primary")# Status indicatorstatus = gr.Markdown(visible=False)# Output tabswith gr.Tabs():with gr.Tab("Clean Text"):clean_text_output = gr.Markdown()with gr.Tab("Summary"):summary_output = gr.Markdown()with gr.Tab("Sentiment"):sentiment_output = gr.Markdown()with gr.Tab("Topics"):topics_output = gr.Markdown()# Examplesgr.Examples(examples=[["https://www.bbc.com/news/technology-67881954", ["summarize", "sentiment"]],["https://arxiv.org/html/2312.17296v1", ["topics", "summarize"]]],inputs=[url_input, analysis_types],)# Event handlersdef on_analyze_click(url, types):if not url:return "Please enter a URL", "", "", ""if not types:return "Please select at least one analysis type", "", "", ""return self.analyzer.analyze_content(url, types)analyze_button.click(fn=lambda: gr.Markdown("⏳ Analysis in progress...", visible=True),outputs=[status]).then(fn=on_analyze_click,inputs=[url_input, analysis_types],outputs=[clean_text_output, summary_output, sentiment_output, topics_output]).then(fn=lambda: gr.Markdown("", visible=False),outputs=[status])return demodef launch(self, server_name=None, server_port=None, share=False):"""Launch the Gradio interface."""demo = self.create_interface()demo.launch(server_name=server_name,server_port=server_port,share=share)
12345678910111213141516171819202122232425262728293031321 unmodified line343536373839404142434445464748499 unmodified lines596061626364656667686970# app.pyfrom smolagents import CodeAgent, HfApiModelfrom tools.final_answer import FinalAnswerToolimport yamlfrom Gradio_UI import GradioUIimport loggingimport sys# Configure logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',handlers=[logging.StreamHandler(sys.stdout),logging.FileHandler('app.log')])logger = logging.getLogger(__name__)def create_agent():"""Create and configure the agent."""try:# Initialize toolsfinal_answer = FinalAnswerTool()# Load promptswith open("prompts.yaml", 'r', encoding='utf-8') as stream:prompt_templates = yaml.safe_load(stream)# Initialize modelmodel = HfApiModel(model_id='Qwen/Qwen2.5-Coder-32B-Instruct',1 unmodified linetemperature=0.5)# Create agentreturn CodeAgent(model=model,tools=[final_answer],max_steps=6,verbosity_level=1,prompt_templates=prompt_templates)except Exception as e:logger.error(f"Failed to create agent: {str(e)}")raisedef main():9 unmodified linesui = GradioUI(agent)ui.launch(server_name="0.0.0.0",server_port=7860,share=False)except Exception as e:logger.error(f"Application failed to start: {str(e)}")sys.exit(1)if __name__ == "__main__":main()1234567891011121314151617181 unmodified line20212223242526272829303132339 unmodified lines4344454647484950515253# app.pyfrom smolagents import CodeAgent, HfApiModelimport loggingfrom Gradio_UI import GradioUI# Configure logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)def create_agent():"""Create and configure the agent."""try:# Initialize modelmodel = HfApiModel(model_id='Qwen/Qwen2.5-Coder-32B-Instruct',1 unmodified linetemperature=0.5)# Create agent with simple configurationreturn CodeAgent(model=model,max_steps=3,verbosity_level=1)except Exception as e:logger.error(f"Failed to create agent: {e}")raisedef main():9 unmodified linesui = GradioUI(agent)ui.launch(server_name="0.0.0.0",server_port=7860)except Exception as e:logger.error(f"Application failed to start: {e}")raiseif __name__ == "__main__":main()
1234567891011121314151617181920# requirements.txtsmolagents>=0.2.0gradio>=4.0.0requests>=2.31.0pytz>=2023.3pyyaml>=6.0.1python-dotenv>=1.0.0beautifulsoup4>=4.12.2numpy>=1.24.3pandas>=2.0.3scikit-learn>=1.3.0nltk>=3.8.1spacy>=3.7.2transformers>=4.35.0torch>=2.0.1tqdm>=4.65.0validators>=0.22.0aiohttp>=3.8.5cachetools>=5.3.1python-dateutil>=2.8.2123456# requirements.txtgradio>=4.0.0requests>=2.31.0beautifulsoup4>=4.12.2smolagents>=0.2.0python-dotenv>=1.0.0
Gradio_UI.py+106-116
app.py+9-26
requirements.txt+2-16