Spaces:
Sleeping
Sleeping
Update app.py
Browse files12342 unmodified lines789101112131415161718192021222324252627289 unmodified lines3839404142434445464748491 unmodified line515253545556575814 unmodified lines73747576777879from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,toolimport datetimeimport requestsimport pytz2 unmodified linesfrom Gradio_UI import GradioUI# Below is my news aggregator tool!@tooldef news_aggregator(keyword: str, max_results: int = 5) -> str:"""A tool that fetches the latest news articles related to a specific keyword.Args:keyword: The topic or keyword to search for (e.g., "AI", "technology").max_results: The maximum number of articles to return (default is 5).Returns:A string containing the titles and URLs of the latest news articles."""try:api_key = 'd43565ac0e674145a22c5f0de4dcd69c'# Construct the API URLurl = f"https://newsapi.org/v2/everything?q={keyword}&pageSize={max_results}&apiKey={api_key}"9 unmodified linesif not articles:return f"No news articles found for the keyword '{keyword}'."# Format the resultsresult = f"Here are the latest news articles about '{keyword}':\n"for i, article in enumerate(articles, 1):title = article.get("title", "No title")url = article.get("url", "#")result += f"{i}. {title}\n {url}\n"return result1 unmodified linereturn f"Error fetching news articles: {str(e)}"except Exception as e:return f"An unexpected error occurred: {str(e)}"final_answer = FinalAnswerTool()# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:14 unmodified lines# Agent and toolsagent = CodeAgent(model=model,tools=[final_answer, news_aggregator], ## add your tools here (don't remove final answer)max_steps=6,verbosity_level=1,grammar=None,123452 unmodified lines891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980819 unmodified lines9192939495969798991001011021031041051061071081091101111121131141 unmodified line11611711811912012114 unmodified lines136137138139140141142from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,toolimport osimport datetimeimport requestsimport pytz2 unmodified linesfrom Gradio_UI import GradioUIfrom transformers import pipelinefrom diffusers import StableDiffusionPipelineimport torchpipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)pipe = pipe.to("cuda") # Use GPU if available@tooldef generate_image(prompt: str) -> str:"""A tool that generates an image based on a text prompt.Args:prompt: The text prompt to generate an image from.Returns:The file path or URL of the generated image."""try:# Generate the imageimage = pipe(prompt).images[0]# Save the image to a fileimage_path = f"generated_images/{prompt[:20]}.png" # Save with a unique nameimage.save(image_path)return image_pathexcept Exception as e:return f"Error generating image: {str(e)}"summarizer = pipeline("summarization")@tooldef summarize_article(article_text: str) -> str:"""A tool that summarizes the content of a news article.Args:article_text: The text content of the article to summarize.Returns:A summarized version of the article."""try:# Summarize the article textsummary = summarizer(article_text, max_length=50, min_length=25, do_sample=False)return summary[0]['summary_text']except Exception as e:return f"Error summarizing article: {str(e)}"@tooldef news_aggregator(keyword: str, max_results: int = 5) -> str:"""A tool that fetches the latest news articles, summarizes them and generates images.Args:keyword: The topic or keyword to search for (e.g., "AI", "technology").max_results: The maximum number of articles to return (default is 5).Returns:A string containing the titles, summaries, and image paths of the latest news articles."""try:api_key = 'd43565ac0e674145a22c5f0de4dcd69c'# Construct the API URLurl = f"https://newsapi.org/v2/everything?q={keyword}&pageSize={max_results}&apiKey={api_key}"9 unmodified linesif not articles:return f"No news articles found for the keyword '{keyword}'."# Process each articleresult = f"Here are the latest news articles about '{keyword}':\n"for i, article in enumerate(articles, 1):title = article.get("title", "No title")url = article.get("url", "#")content = article.get("content", "") # Get the article content# Summarize the articlesummary = summarize_article(content)# Generate an image based on the titleimage_path = generate_image(title)# Format the resultsresult += f"{i}. {title}\n"result += f" Summary: {summary}\n"result += f" Image: {image_path}\n"result += f" URL: {url}\n"return result1 unmodified linereturn f"Error fetching news articles: {str(e)}"except Exception as e:return f"An unexpected error occurred: {str(e)}"final_answer = FinalAnswerTool()# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:14 unmodified lines# Agent and toolsagent = CodeAgent(model=model,tools=[final_answer, news_aggregator, summarize_article, generate_image], ## add your tools here (don't remove final answer)max_steps=6,verbosity_level=1,grammar=None,
app.py+71-8