Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,185 +1,237 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
from transformers import pipeline
|
| 3 |
from gtts import gTTS
|
| 4 |
import time
|
| 5 |
import os
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
summarization_pipeline = pipeline("summarization", model="RussianNLP/FRED-T5-Summarizer")
|
| 10 |
|
| 11 |
-
# Task
|
| 12 |
-
def
|
| 13 |
if not text.strip():
|
| 14 |
-
return "
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
if task == "Sentiment Analysis":
|
| 19 |
-
result = sentiment_pipeline(text)[0]
|
| 20 |
-
label = result['label']
|
| 21 |
-
score = round(result['score'], 3)
|
| 22 |
-
emoji = "π" if label == "POSITIVE" else "π"
|
| 23 |
-
confidence_bar = "β" * int(score * 10) + "β" * (10 - int(score * 10))
|
| 24 |
-
output = f"""
|
| 25 |
-
{emoji} **Sentiment Analysis Results**
|
| 26 |
-
|
| 27 |
-
**Label:** {label}
|
| 28 |
-
**Confidence:** {score} ({score*100:.1f}%)
|
| 29 |
-
**Visual:** {confidence_bar}
|
| 30 |
-
|
| 31 |
-
**Interpretation:** This text expresses a {label.lower()} sentiment with {score*100:.1f}% confidence.
|
| 32 |
-
""".strip()
|
| 33 |
-
return output, None, gr.update(visible=False)
|
| 34 |
-
|
| 35 |
-
elif task == "Summarization":
|
| 36 |
-
result = summarization_pipeline(text, max_length=100, min_length=30, do_sample=False)
|
| 37 |
-
summary = result[0]['summary_text']
|
| 38 |
-
original_words = len(text.split())
|
| 39 |
-
summary_words = len(summary.split())
|
| 40 |
-
compression_ratio = round((1 - summary_words/original_words) * 100, 1)
|
| 41 |
-
output = f"""
|
| 42 |
-
π **Text Summarization Results**
|
| 43 |
-
|
| 44 |
-
**Summary:**
|
| 45 |
-
{summary}
|
| 46 |
-
|
| 47 |
-
**Statistics:**
|
| 48 |
-
β’ Original: {original_words} words
|
| 49 |
-
β’ Summary: {summary_words} words
|
| 50 |
-
β’ Compression: {compression_ratio}% reduction
|
| 51 |
-
""".strip()
|
| 52 |
-
return output, None, gr.update(visible=False)
|
| 53 |
|
| 54 |
-
|
| 55 |
-
tts = gTTS(text)
|
| 56 |
-
filename = "tts_output.mp3"
|
| 57 |
-
tts.save(filename)
|
| 58 |
-
word_count = len(text.split())
|
| 59 |
-
char_count = len(text)
|
| 60 |
-
output = f"""
|
| 61 |
-
π **Text-to-Speech Generated Successfully!**
|
| 62 |
-
|
| 63 |
-
**Input Statistics:**
|
| 64 |
-
β’ Words: {word_count}
|
| 65 |
-
β’ Characters: {char_count}
|
| 66 |
-
β’ Estimated duration: ~{word_count * 0.5:.1f} seconds
|
| 67 |
-
|
| 68 |
-
**Audio file ready for playback below** β¬οΈ
|
| 69 |
-
""".strip()
|
| 70 |
-
return output, filename, gr.update(visible=True, value=filename)
|
| 71 |
-
|
| 72 |
-
# Handle button click
|
| 73 |
-
def handle_task_processing(task, text):
|
| 74 |
if not text.strip():
|
| 75 |
-
return "
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
# Custom CSS
|
| 80 |
-
custom_css = """<style>
|
| 81 |
-
/* Same CSS as before, trimmed for brevity */
|
| 82 |
-
body, .gradio-container {
|
| 83 |
-
background-color: #0a0a0a !important;
|
| 84 |
-
color: #ffffff !important;
|
| 85 |
-
}
|
| 86 |
-
</style>"""
|
| 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 |
-
lines=8,
|
| 120 |
-
label="π Input Text",
|
| 121 |
-
placeholder="Enter your text here...",
|
| 122 |
-
info="Type or paste the text you want to process"
|
| 123 |
)
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
gr.Markdown("## π Results", elem_classes=["results-header"])
|
| 129 |
-
|
| 130 |
-
with gr.Row():
|
| 131 |
-
with gr.Column(scale=2):
|
| 132 |
-
output_text = gr.Textbox(
|
| 133 |
-
label="π Analysis Results",
|
| 134 |
-
lines=8,
|
| 135 |
-
interactive=False
|
| 136 |
)
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
| 143 |
)
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
history + [
|
| 156 |
-
(
|
| 157 |
-
message,
|
| 158 |
-
f"π§ Sentiment: {sentiment_pipeline(message)[0]['label']} (Confidence: {round(sentiment_pipeline(message)[0]['score'], 2)})"
|
| 159 |
)
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
| 165 |
)
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
-
# Launch
|
| 180 |
if __name__ == "__main__":
|
| 181 |
-
demo
|
| 182 |
-
|
| 183 |
-
debug=True,
|
| 184 |
-
show_error=True
|
| 185 |
-
)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import openai
|
| 3 |
from transformers import pipeline
|
| 4 |
from gtts import gTTS
|
| 5 |
import time
|
| 6 |
import os
|
| 7 |
|
| 8 |
+
# OpenAI Chatbot Class
|
| 9 |
+
class OpenAIChatbot:
|
| 10 |
+
def __init__(self, api_key: str = None):
|
| 11 |
+
self.client = None
|
| 12 |
+
self.model = "gpt-3.5-turbo"
|
| 13 |
+
if api_key:
|
| 14 |
+
self.set_api_key(api_key)
|
| 15 |
+
|
| 16 |
+
def set_api_key(self, api_key: str):
|
| 17 |
+
try:
|
| 18 |
+
self.client = openai.OpenAI(api_key=api_key)
|
| 19 |
+
self.client.models.list()
|
| 20 |
+
return "β
API Key set successfully!"
|
| 21 |
+
except Exception as e:
|
| 22 |
+
return f"β Error: {str(e)}"
|
| 23 |
+
|
| 24 |
+
def stream_chat(self, message: str, history: list, system_prompt: str = ""):
|
| 25 |
+
if not self.client:
|
| 26 |
+
history.append([message, "Please set your OpenAI API key first!"])
|
| 27 |
+
yield history
|
| 28 |
+
return
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
messages = []
|
| 32 |
+
if system_prompt.strip():
|
| 33 |
+
messages.append({"role": "system", "content": system_prompt})
|
| 34 |
+
|
| 35 |
+
for chat_pair in history:
|
| 36 |
+
if len(chat_pair) >= 2:
|
| 37 |
+
messages.append({"role": "user", "content": chat_pair[0]})
|
| 38 |
+
messages.append({"role": "assistant", "content": chat_pair[1]})
|
| 39 |
+
|
| 40 |
+
messages.append({"role": "user", "content": message})
|
| 41 |
+
history.append([message, ""])
|
| 42 |
+
|
| 43 |
+
stream = self.client.chat.completions.create(
|
| 44 |
+
model=self.model,
|
| 45 |
+
messages=messages,
|
| 46 |
+
max_tokens=1000,
|
| 47 |
+
temperature=0.7,
|
| 48 |
+
stream=True
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
bot_response = ""
|
| 52 |
+
for chunk in stream:
|
| 53 |
+
if chunk.choices[0].delta.content is not None:
|
| 54 |
+
bot_response += chunk.choices[0].delta.content
|
| 55 |
+
history[-1] = [message, bot_response]
|
| 56 |
+
yield history
|
| 57 |
+
time.sleep(0.02)
|
| 58 |
+
|
| 59 |
+
except Exception as e:
|
| 60 |
+
history[-1] = [message, f"Error: {str(e)}"]
|
| 61 |
+
yield history
|
| 62 |
+
|
| 63 |
+
# Load Transformers models
|
| 64 |
+
sentiment_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
|
| 65 |
summarization_pipeline = pipeline("summarization", model="RussianNLP/FRED-T5-Summarizer")
|
| 66 |
|
| 67 |
+
# Task functions
|
| 68 |
+
def analyze_sentiment(text):
|
| 69 |
if not text.strip():
|
| 70 |
+
return "Please enter text to analyze."
|
| 71 |
+
|
| 72 |
+
result = sentiment_pipeline(text)[0]
|
| 73 |
+
return f"**Sentiment:** {result['label']}\n**Confidence:** {result['score']:.3f}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
def summarize_text(text):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
if not text.strip():
|
| 77 |
+
return "Please enter text to summarize."
|
| 78 |
+
|
| 79 |
+
result = summarization_pipeline(text, max_length=100, min_length=30, do_sample=False)
|
| 80 |
+
return result[0]['summary_text']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
def text_to_speech(text):
|
| 83 |
+
if not text.strip():
|
| 84 |
+
return "Please enter text for TTS.", None
|
| 85 |
+
|
| 86 |
+
tts = gTTS(text)
|
| 87 |
+
filename = "tts_output.mp3"
|
| 88 |
+
tts.save(filename)
|
| 89 |
+
return f"Audio generated for {len(text.split())} words.", filename
|
| 90 |
+
|
| 91 |
+
# Initialize chatbot
|
| 92 |
+
chatbot = OpenAIChatbot()
|
| 93 |
+
|
| 94 |
+
# Create interface
|
| 95 |
+
def create_interface():
|
| 96 |
+
with gr.Blocks(title="AI Assistant") as demo:
|
| 97 |
+
gr.Markdown("# π€ Multi-Task AI Assistant")
|
| 98 |
+
|
| 99 |
+
with gr.Tabs():
|
| 100 |
+
# OpenAI Chat Tab
|
| 101 |
+
with gr.TabItem("π¬ OpenAI Chat"):
|
| 102 |
+
with gr.Row():
|
| 103 |
+
api_key_input = gr.Textbox(
|
| 104 |
+
label="OpenAI API Key",
|
| 105 |
+
type="password",
|
| 106 |
+
placeholder="sk-..."
|
| 107 |
)
|
| 108 |
+
set_key_btn = gr.Button("Set Key")
|
| 109 |
+
|
| 110 |
+
status = gr.Textbox(label="Status", interactive=False)
|
| 111 |
+
|
| 112 |
+
with gr.Row():
|
| 113 |
+
model_dropdown = gr.Dropdown(
|
| 114 |
+
choices=["gpt-3.5-turbo", "gpt-4"],
|
| 115 |
+
value="gpt-3.5-turbo",
|
| 116 |
+
label="Model"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
)
|
| 118 |
+
system_prompt = gr.Textbox(
|
| 119 |
+
label="System Prompt",
|
| 120 |
+
placeholder="You are a helpful assistant..."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
)
|
| 122 |
+
|
| 123 |
+
chatbot_interface = gr.Chatbot(label="Chat", height=400)
|
| 124 |
+
|
| 125 |
+
with gr.Row():
|
| 126 |
+
msg_input = gr.Textbox(
|
| 127 |
+
placeholder="Type your message...",
|
| 128 |
+
show_label=False,
|
| 129 |
+
scale=4
|
| 130 |
)
|
| 131 |
+
send_btn = gr.Button("Send", variant="primary")
|
| 132 |
+
clear_btn = gr.Button("Clear")
|
| 133 |
+
|
| 134 |
+
# Sentiment Analysis Tab
|
| 135 |
+
with gr.TabItem("π Sentiment Analysis"):
|
| 136 |
+
with gr.Row():
|
| 137 |
+
with gr.Column():
|
| 138 |
+
sentiment_input = gr.Textbox(
|
| 139 |
+
label="Text to analyze",
|
| 140 |
+
lines=5,
|
| 141 |
+
placeholder="Enter text to analyze sentiment..."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
)
|
| 143 |
+
sentiment_btn = gr.Button("Analyze", variant="primary")
|
| 144 |
+
|
| 145 |
+
with gr.Column():
|
| 146 |
+
sentiment_output = gr.Textbox(
|
| 147 |
+
label="Results",
|
| 148 |
+
lines=5,
|
| 149 |
+
interactive=False
|
| 150 |
)
|
| 151 |
+
|
| 152 |
+
# Summarization Tab
|
| 153 |
+
with gr.TabItem("π Summarization"):
|
| 154 |
+
with gr.Row():
|
| 155 |
+
with gr.Column():
|
| 156 |
+
summary_input = gr.Textbox(
|
| 157 |
+
label="Text to summarize",
|
| 158 |
+
lines=8,
|
| 159 |
+
placeholder="Enter long text to summarize..."
|
| 160 |
+
)
|
| 161 |
+
summary_btn = gr.Button("Summarize", variant="primary")
|
| 162 |
+
|
| 163 |
+
with gr.Column():
|
| 164 |
+
summary_output = gr.Textbox(
|
| 165 |
+
label="Summary",
|
| 166 |
+
lines=8,
|
| 167 |
+
interactive=False
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# Text-to-Speech Tab
|
| 171 |
+
with gr.TabItem("π Text-to-Speech"):
|
| 172 |
+
with gr.Row():
|
| 173 |
+
with gr.Column():
|
| 174 |
+
tts_input = gr.Textbox(
|
| 175 |
+
label="Text to convert",
|
| 176 |
+
lines=5,
|
| 177 |
+
placeholder="Enter text to convert to speech..."
|
| 178 |
+
)
|
| 179 |
+
tts_btn = gr.Button("Generate Speech", variant="primary")
|
| 180 |
+
|
| 181 |
+
with gr.Column():
|
| 182 |
+
tts_status = gr.Textbox(label="Status", interactive=False)
|
| 183 |
+
tts_audio = gr.Audio(label="Generated Audio")
|
| 184 |
+
|
| 185 |
+
# Event handlers
|
| 186 |
+
def send_message(message, history, system_prompt):
|
| 187 |
+
if not message.strip():
|
| 188 |
+
return history, ""
|
| 189 |
+
|
| 190 |
+
for updated_history in chatbot.stream_chat(message, history, system_prompt):
|
| 191 |
+
yield updated_history, ""
|
| 192 |
+
|
| 193 |
+
# OpenAI Chat events
|
| 194 |
+
set_key_btn.click(
|
| 195 |
+
chatbot.set_api_key,
|
| 196 |
+
inputs=[api_key_input],
|
| 197 |
+
outputs=[status]
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
send_btn.click(
|
| 201 |
+
send_message,
|
| 202 |
+
inputs=[msg_input, chatbot_interface, system_prompt],
|
| 203 |
+
outputs=[chatbot_interface, msg_input]
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
msg_input.submit(
|
| 207 |
+
send_message,
|
| 208 |
+
inputs=[msg_input, chatbot_interface, system_prompt],
|
| 209 |
+
outputs=[chatbot_interface, msg_input]
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
clear_btn.click(lambda: None, outputs=[chatbot_interface])
|
| 213 |
+
|
| 214 |
+
# Other task events
|
| 215 |
+
sentiment_btn.click(
|
| 216 |
+
analyze_sentiment,
|
| 217 |
+
inputs=[sentiment_input],
|
| 218 |
+
outputs=[sentiment_output]
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
summary_btn.click(
|
| 222 |
+
summarize_text,
|
| 223 |
+
inputs=[summary_input],
|
| 224 |
+
outputs=[summary_output]
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
tts_btn.click(
|
| 228 |
+
text_to_speech,
|
| 229 |
+
inputs=[tts_input],
|
| 230 |
+
outputs=[tts_status, tts_audio]
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
return demo
|
| 234 |
|
|
|
|
| 235 |
if __name__ == "__main__":
|
| 236 |
+
demo = create_interface()
|
| 237 |
+
demo.launch(share=True)
|
|
|
|
|
|
|
|
|