Spaces:
Sleeping
Sleeping
File size: 4,937 Bytes
63f606d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | import os
import openai
import pydantic
import instructor
import gradio as gr
from dotenv import load_dotenv
# Load environment variables from .env file for local development
load_dotenv()
# --- Pydantic Model for Structured Output ---
# Defines the structure of the summary we want the AI to generate.
class Summary(pydantic.BaseModel):
one_paragraph_summary: str = pydantic.Field(
..., description="A concise, one-paragraph summary of the original text."
)
three_key_takeaways: list[str] = pydantic.Field(
...,
description="A list of exactly three key takeaways from the text.",
min_items=3,
max_items=3,
)
# --- OpenAI API Key Management ---
def get_openai_api_key():
"""
Retrieves the OpenAI API key from environment variables.
This is compatible with Hugging Face Spaces secrets.
"""
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError(
"OpenAI API key not found. Please set the OPENAI_API_KEY environment "
"variable or add it to your Hugging Face Space secrets."
)
return api_key
# --- Core Summarization Logic ---
def summarize(text: str) -> Summary:
"""
Generates a structured summary for the given text using an OpenAI model.
Args:
text: The user-provided text to be summarized.
Returns:
A Pydantic 'Summary' object containing the structured summary.
"""
try:
# Patch the OpenAI client with instructor to get structured output
client = instructor.patch(openai.OpenAI(api_key=get_openai_api_key()))
# Generate the structured summary
summary_response = client.chat.completions.create(
model="gpt-4-turbo",
response_model=Summary,
messages=[
{
"role": "system",
"content": """
You are an expert summarization AI. Your goal is to generate an accurate,
informative summary that simplifies text to maximize understanding and
retention of key points.
When summarizing the user's text, adhere to these principles:
1. Distill Complex Information: Break down complex ideas into manageable chunks.
2. Minimize Cognitive Load: Condense the information to its core essence.
3. Identify Key Information: Focus on crucial details and cut extraneous information.
4. Prevent Information Overload: Emphasize only the most essential points.
5. Ensure Clarity and Structure: Use logical flow and clear language.
Your final output must be a one-paragraph summary of the original text
and exactly three key takeaways.
""",
},
{"role": "user", "content": text},
],
)
return summary_response
except Exception as e:
print(f"An error occurred: {e}")
# Return an error message in the same structure to be displayed in the UI
return Summary(
one_paragraph_summary="An error occurred during summarization.",
three_key_takeaways=[
"Could not generate takeaway 1.",
"Could not generate takeaway 2.",
"Could not generate takeaway 3.",
],
)
# --- Gradio Interface ---
def create_gradio_interface():
"""
Creates and launches the Gradio web interface for the summarization agent.
"""
def format_summary_for_ui(text: str):
"""
Wrapper function to call the summarizer and format the output for Gradio.
"""
if not text.strip():
return "Please enter some text to summarize."
summary_data = summarize(text)
# Format the output as Markdown for display
markdown_output = f"""
### Summary
{summary_data.one_paragraph_summary}
### Key Takeaways
- {summary_data.three_key_takeaways[0]}
- {summary_data.three_key_takeaways[1]}
- {summary_data.three_key_takeaways[2]}
"""
return markdown_output
interface = gr.Interface(
fn=format_summary_for_ui,
inputs=gr.Textbox(
lines=15,
label="Text to Summarize",
placeholder="Paste your text here...",
),
outputs=gr.Markdown(label="Generated Summary"),
title="AI Text Summarization Agent",
description=(
"Enter any text to generate a concise one-paragraph summary and three key takeaways. "
"This agent is designed to distill complex information into an easily digestible format."
),
allow_flagging="never",
)
return interface
if __name__ == "__main__":
app = create_gradio_interface()
app.launch()
|