myai-summarizer / app.py
sivan26's picture
create app.py
db24609 verified
# app.py
import gradio as gr
from transformers import pipeline
# --- 1. Load the Text Summarization Model ---
# We're using a pre-trained summarization model from Hugging Face.
# 'sshleifer/distilbart-cnn-12-6' is a good balance of speed and quality.
# The 'pipeline' function simplifies using these models.
print("Loading summarization model... This may take a moment.")
try:
summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
print("Model loaded successfully!")
except Exception as e:
print(f"Error loading model: {e}")
# Fallback or exit if the model can't be loaded, or handle gracefully.
# For this demo, we'll let it fail for simplicity in error handling.
summarizer = None # Ensure summarizer is None if loading fails
# --- 2. Define the Summarization Function ---
# This function will be called when the user clicks the 'Summarize' button.
def summarize_text(input_text):
"""
Takes an input string and returns a concise summary.
"""
if not input_text.strip(): # Check if the input text is empty or just whitespace
return "Please enter some text to summarize."
if summarizer is None:
return "Summarization model failed to load. Please try again later or check server logs."
try:
# The summarizer pipeline returns a list of dictionaries.
# We're interested in the 'summary_text' key from the first item.
summary = summarizer(input_text, max_length=150, min_length=30, do_sample=False)
return summary[0]['summary_text']
except Exception as e:
# Basic error handling for summarization issues
return f"An error occurred during summarization: {e}"
# --- 3. Create the Gradio Interface ---
# Gradio makes it easy to build a web UI for machine learning models.
# `fn`: The function to call when the interface is used.
# `inputs`: The type of input component (here, a Textbox).
# `outputs`: The type of output component (here, a Textbox).
# `title` and `description` are used for the app's heading and explanation.
iface = gr.Interface(
fn=summarize_text,
inputs=gr.Textbox(lines=10, placeholder="Paste your text here to get a summary...", label="Input Text"),
outputs=gr.Textbox(lines=7, label="Summary"),
title="Simple AI Text Summarizer",
description=(
"This demo application uses a Hugging Face pre-trained model (DistilBART) "
"to generate a concise summary of your input text. "
"Simply type or paste your text into the box below and click 'Submit'."
),
live=False # Set to True if you want real-time summarization as you type
)
# --- 4. Launch the Gradio App ---
# This line starts the web server for the Gradio app.
# share=True generates a public link (useful for sharing demos temporarily).
# debug=True provides more detailed logging in the console.
if __name__ == "__main__":
iface.launch(share=False, debug=False)