BookSumBeta / app.py
npc0's picture
Update app.py
4967799 verified
raw
history blame
6.73 kB
import gradio as gr
import requests
import json
import os
from datetime import datetime
# API configuration
GROQ_API_KEY = os.getenv('GROQ_API_KEY')
headers = {
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json"
}
def get_summary(user_input, conversation_id, request: gr.Request):
"""Generate summary using GROQ API"""
if not user_input.strip():
return "Please enter some text to summarize.", conversation_id
try:
# GROQ API call
url = "https://api.groq.com/openai/v1/chat/completions"
data = {
"model": "mixtral-8x7b-32768",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant that provides concise and informative summaries of text."
},
{
"role": "user",
"content": f"Please provide a comprehensive summary of the following text:\n\n{user_input}"
}
],
"max_tokens": 1000,
"temperature": 0.3
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
result = response.json()
summary = result['choices'][0]['message']['content']
# Add to conversation history
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
conversation_id.append({
"timestamp": timestamp,
"input": user_input[:100] + "..." if len(user_input) > 100 else user_input,
"summary": summary
})
return summary, conversation_id
else:
return f"Error: {response.status_code} - {response.text}", conversation_id
except Exception as e:
return f"An error occurred: {str(e)}", conversation_id
def format_history(conversation_id):
"""Format conversation history for display"""
if not conversation_id:
return "No summaries generated yet."
history = ""
for i, item in enumerate(conversation_id, 1):
history += f"**Summary {i}** ({item['timestamp']})\n"
history += f"*Input:* {item['input']}\n"
history += f"*Summary:* {item['summary']}\n\n---\n\n"
return history
# Custom CSS for better styling
css = """
.gradio-container {
max-width: 1200px !important;
}
.summary-input {
min-height: 200px;
}
.summary-output {
min-height: 150px;
}
.history-panel {
max-height: 400px;
overflow-y: auto;
}
"""
# Create the main interface
def create_app():
with gr.Blocks(
css=css,
title="πŸ“š BookSum Beta - AI Text Summarizer",
theme=gr.themes.Soft()
) as app:
# Initialize conversation state
conversation_state = gr.State([])
# Header
gr.Markdown(
"""
# πŸ“š BookSum Beta
## AI-Powered Text Summarization Tool
Enter any text below and get an intelligent, comprehensive summary powered by advanced AI.
"""
)
with gr.Row():
with gr.Column(scale=2):
# Input section
with gr.Group():
gr.Markdown("### πŸ“ Input Text")
text_input = gr.Textbox(
label="Enter text to summarize",
placeholder="Paste your text, article, or document here...",
lines=10,
elem_classes=["summary-input"]
)
with gr.Row():
summarize_btn = gr.Button(
"✨ Generate Summary",
variant="primary",
size="lg"
)
clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
# Output section
with gr.Group():
gr.Markdown("### πŸ“„ Summary")
summary_output = gr.Textbox(
label="Generated Summary",
lines=8,
elem_classes=["summary-output"],
interactive=False
)
with gr.Column(scale=1):
# History sidebar
with gr.Group():
gr.Markdown("### πŸ“œ History")
history_display = gr.Markdown(
"No summaries generated yet.",
elem_classes=["history-panel"]
)
refresh_history_btn = gr.Button("πŸ”„ Refresh History", size="sm")
# Footer
gr.Markdown(
"""
---
*Powered by GROQ API | Built with Gradio 5*
"""
)
# Event handlers
summarize_btn.click(
fn=get_summary,
inputs=[text_input, conversation_state],
outputs=[summary_output, conversation_state]
).then(
fn=format_history,
inputs=[conversation_state],
outputs=[history_display]
)
clear_btn.click(
lambda: ("", ""),
outputs=[text_input, summary_output]
)
refresh_history_btn.click(
fn=format_history,
inputs=[conversation_state],
outputs=[history_display]
)
# Allow Enter key to submit (but only if text is not empty)
text_input.submit(
fn=get_summary,
inputs=[text_input, conversation_state],
outputs=[summary_output, conversation_state]
).then(
fn=format_history,
inputs=[conversation_state],
outputs=[history_display]
)
return app
# Authentication function
def authenticate(username, password):
"""Simple authentication - replace with your logic"""
# For demo purposes - replace with your actual authentication
valid_users = {
"admin": "password123",
"user": "userpass",
"demo": "demo"
}
return username in valid_users and valid_users[username] == password
if __name__ == "__main__":
app = create_app()
# Launch with authentication
app.launch(
auth=authenticate,
auth_message="Please log in to access BookSum Beta",
share=False,
server_name="0.0.0.0",
server_port=7860,
show_error=True
)