Certainly! Below is a Python script that creates a Gradio interface as per your requirements. This interface allows you to input URLs, optional title, additional content to include, and images to add. It then fetches the text from the provided URLs, generates a news article using the Ollama AI model, and displays the generated articles in a list. You can select an article from the list to view its full content.
import gradio as gr
import ollama
import requests
from bs4 import BeautifulSoup
def fetch_text_from_url(url):
try:
response = requests.get(url)
response.raise_for_status()
# Parse HTML content
soup = BeautifulSoup(response.text, 'html.parser')
# Remove unnecessary tags
[s.extract() for s in soup(['style', 'script', 'head', 'title', 'meta', '[document]'])]
# Extract text
article_text = ' '.join(soup.stripped_strings)
return article_text
except Exception as e:
print(f"Error fetching URL {url}: {e}")
return ''
def generate_article(title, urls, include_text, images):
# Fetch text from URLs
combined_text = ''
for url in urls:
text = fetch_text_from_url(url)
combined_text += text + '\n\n'
# Include additional text
if include_text:
combined_text += include_text + '\n\n'
# Include images
if images:
combined_text += 'Include the following images in the article: ' + ', '.join(images) + '\n\n'
# Prepare prompt for AI
prompt = f"{title}\n\n{combined_text}" if title else combined_text
messages = [
{'role': 'system', 'content': 'You are a helpful assistant that writes news articles.'},
{'role': 'user', 'content': prompt}
]
# Generate article using Ollama
response = ollama.chat(model='llama3.1', messages=messages)
article = response['message']['content']
return article
def generate_and_store_article(title, urls, include_text, images, articles_list):
article_text = generate_article(title, urls, include_text, images)
article_entry = {'title': title or f"Article {len(articles_list)+1}", 'article': article_text}
articles_list.append(article_entry)
titles = [a['title'] for a in articles_list]
return titles, articles_list
def display_article(selected_title, articles_list):
for article in articles_list:
if article['title'] == selected_title:
return article['article']
return 'Article not found.'
with gr.Blocks() as demo:
articles_list = gr.State([]) # Initialize state to store articles
with gr.Tab("News"):
title_list = gr.Dropdown(label="Articles", choices=[], interactive=True)
article_display = gr.Textbox(label="Article Text", lines=20)
# Update article display when a new title is selected
title_list.change(fn=display_article, inputs=[title_list, articles_list], outputs=article_display)
with gr.Tab("Management"):
title_input = gr.Textbox(label="Title (optional)")
urls_input = gr.Textbox(label="URLs (separate multiple URLs with commas)")
include_input = gr.Textbox(label="What to include (optional)")
images_input = gr.Textbox(label="Images to add (URLs, optional)")
generate_button = gr.Button("Generate")
def on_generate(title, urls_text, include_text, images_text, articles_list):
urls = [url.strip() for url in urls_text.split(',') if url.strip()]
images = [img.strip() for img in images_text.split(',') if img.strip()] if images_text else []
titles, articles_list = generate_and_store_article(title, urls, include_text, images, articles_list)
return gr.Dropdown.update(choices=titles), articles_list
# When the generate button is clicked, generate the article and update the titles list
generate_button.click(
fn=on_generate,
inputs=[title_input, urls_input, include_input, images_input, articles_list],
outputs=[title_list, articles_list]
)
demo.launch()
Explanation:
-
Imports:
gradio for the interface.
ollama for AI-generated text.
requests and BeautifulSoup for fetching and parsing webpage content.
-
Functions:
fetch_text_from_url(url): Fetches and extracts text from a given URL.
generate_article(...): Compiles text from URLs and additional input, then generates an article using Ollama.
generate_and_store_article(...): Stores the generated article and updates the list of article titles.
display_article(...): Retrieves and displays the full text of a selected article.
-
Interface Structure:
- News Tab:
title_list: Dropdown to select from generated article titles.
article_display: Textbox to display the full article text.
- Management Tab:
- Inputs for optional title, URLs, additional content, and images.
generate_button: Triggers article generation.
- State Management:
articles_list: A gr.State object to store articles between interactions.
Instructions:
-
Install Dependencies:
Ensure you have all the necessary libraries installed:
pip install gradio ollama requests beautifulsoup4
-
Run the Script:
Save the script to a file, e.g., news_generator.py, and run:
python news_generator.py
-
Use the Interface:
- Navigate to the provided local URL in your web browser.
- Management Tab:
- Enter URLs from which you want to fetch content.
- Optionally, add a title, additional content to include, and images URLs.
- Click the "Generate" button.
- News Tab:
- Select from the list of generated articles.
- View the full text of the selected article.
Notes:
-
URL Input:
- Enter one or multiple URLs separated by commas.
- Ensure the URLs are accessible and contain readable text content.
-
Images:
- Currently, images are mentioned in the generated text but are not displayed.
- Implementing actual image handling would require additional code to fetch and display images.
-
Ollama AI Model:
- Make sure you have access to the
llama3.1 model or adjust the model name accordingly.
- If you want to see the streaming output, you can modify the
generate_article function to handle streaming responses from Ollama.
-
Error Handling:
- The script includes basic error handling for URL fetching.
- For robust applications, consider adding more comprehensive error checks and user feedback.
Customization:
-
Improving Content Extraction:
- The method used to extract text from web pages is basic.
- For better results, consider using specialized libraries like
newspaper3k or readability.
pip install newspaper3k
And modify the fetch_text_from_url function:
from newspaper import Article
def fetch_text_from_url(url):
try:
article = Article(url)
article.download()
article.parse()
return article.text
except Exception as e:
print(f"Error fetching URL {url}: {e}")
return ''
-
Enhancing the AI Prompt:
- You can adjust the prompt sent to the AI to tailor the style and content of the generated articles.
- For example, specify the desired tone, length, or structure.
-
Adding HTML Rendering:
- To display the articles with rich formatting, you can use
gr.HTML instead of gr.Textbox for the article_display.
article_display = gr.HTML(label="Article Text")
Ensure that the generated content is safe to render as HTML.
Conclusion:
This script provides a starting point for your news article generator using Gradio and Ollama. You can further enhance it by improving the content extraction, handling images, and customizing the AI prompt to suit your specific needs.