Spaces:
Sleeping
Sleeping
File size: 6,725 Bytes
615f98d 4967799 b8becf7 4967799 b8becf7 4967799 b8becf7 4967799 b8becf7 4967799 e594988 4967799 0612cdd 4967799 0612cdd 4967799 0612cdd 4967799 0612cdd 4967799 0612cdd b8becf7 4967799 0612cdd 4967799 e594988 4967799 b8becf7 4967799 |
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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
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
) |