Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,237 +1,107 @@
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
class OpenAIChatbot:
|
| 10 |
-
def __init__(self,
|
| 11 |
-
self.
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 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 |
-
|
| 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 |
-
|
| 47 |
temperature=0.7,
|
| 48 |
-
|
| 49 |
)
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
if
|
| 54 |
-
|
| 55 |
-
history[-1] =
|
| 56 |
yield history
|
| 57 |
time.sleep(0.02)
|
| 58 |
-
|
| 59 |
except Exception as e:
|
| 60 |
-
history[-1] =
|
| 61 |
yield history
|
| 62 |
|
| 63 |
-
|
| 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 |
-
#
|
| 68 |
-
def
|
| 69 |
if not text.strip():
|
| 70 |
-
return "Please enter text
|
| 71 |
-
|
| 72 |
-
result = sentiment_pipeline(text)[0]
|
| 73 |
-
return f"**Sentiment:** {result['label']}\n**Confidence:** {result['score']:.3f}"
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
return "
|
| 78 |
-
|
| 79 |
-
result = summarization_pipeline(text, max_length=100, min_length=30, do_sample=False)
|
| 80 |
-
return result[0]['summary_text']
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
return
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
|
| 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)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import openai
|
| 3 |
+
import time
|
| 4 |
from transformers import pipeline
|
| 5 |
from gtts import gTTS
|
|
|
|
| 6 |
import os
|
| 7 |
|
| 8 |
+
# ✅ Set your OpenAI API key here
|
| 9 |
+
openai.api_key = "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" # <<< REPLACE THIS WITH YOUR KEY
|
| 10 |
+
|
| 11 |
+
# Load pipelines
|
| 12 |
+
sentiment_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
|
| 13 |
+
summarization_pipeline = pipeline("summarization", model="facebook/bart-large-cnn")
|
| 14 |
+
|
| 15 |
+
# Chatbot class
|
| 16 |
class OpenAIChatbot:
|
| 17 |
+
def __init__(self, model="gpt-3.5-turbo"):
|
| 18 |
+
self.model = model
|
| 19 |
+
|
| 20 |
+
def set_model(self, model_name):
|
| 21 |
+
self.model = model_name
|
| 22 |
+
return f"Model set to {model_name}"
|
| 23 |
+
|
| 24 |
+
def stream_chat(self, message, history, system_prompt=""):
|
| 25 |
+
if not message.strip():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
yield history
|
| 27 |
return
|
| 28 |
+
|
| 29 |
+
messages = [{"role": "system", "content": system_prompt}] if system_prompt else []
|
| 30 |
+
for user, bot in history:
|
| 31 |
+
messages += [{"role": "user", "content": user}, {"role": "assistant", "content": bot}]
|
| 32 |
+
messages.append({"role": "user", "content": message})
|
| 33 |
+
|
| 34 |
+
history.append([message, ""])
|
| 35 |
+
|
| 36 |
try:
|
| 37 |
+
response = openai.chat.completions.create(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
model=self.model,
|
| 39 |
messages=messages,
|
| 40 |
+
stream=True,
|
| 41 |
temperature=0.7,
|
| 42 |
+
max_tokens=1000
|
| 43 |
)
|
| 44 |
+
bot_reply = ""
|
| 45 |
+
for chunk in response:
|
| 46 |
+
delta = chunk.choices[0].delta
|
| 47 |
+
if delta and delta.content:
|
| 48 |
+
bot_reply += delta.content
|
| 49 |
+
history[-1][1] = bot_reply
|
| 50 |
yield history
|
| 51 |
time.sleep(0.02)
|
|
|
|
| 52 |
except Exception as e:
|
| 53 |
+
history[-1][1] = f"Error: {str(e)}"
|
| 54 |
yield history
|
| 55 |
|
| 56 |
+
chatbot = OpenAIChatbot()
|
|
|
|
|
|
|
| 57 |
|
| 58 |
+
# Multi-task handler
|
| 59 |
+
def perform_task(task, text):
|
| 60 |
if not text.strip():
|
| 61 |
+
return "⚠️ Please enter some text.", None, gr.update(visible=False)
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
if task == "Sentiment Analysis":
|
| 64 |
+
result = sentiment_pipeline(text)[0]
|
| 65 |
+
return f"Label: {result['label']} | Confidence: {round(result['score'], 3)}", None, gr.update(visible=False)
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
elif task == "Summarization":
|
| 68 |
+
result = summarization_pipeline(text, max_length=100, min_length=30, do_sample=False)
|
| 69 |
+
return result[0]['summary_text'], None, gr.update(visible=False)
|
| 70 |
+
|
| 71 |
+
elif task == "Text-to-Speech":
|
| 72 |
+
tts = gTTS(text)
|
| 73 |
+
file_path = "tts_output.mp3"
|
| 74 |
+
tts.save(file_path)
|
| 75 |
+
return "Audio generated successfully.", file_path, gr.update(visible=True, value=file_path)
|
| 76 |
+
|
| 77 |
+
# Interface
|
| 78 |
+
with gr.Blocks() as demo:
|
| 79 |
+
gr.Markdown("# 🤖 Multi-Task AI Assistant + OpenAI Chatbot")
|
| 80 |
+
|
| 81 |
+
with gr.Tab("AI Tasks"):
|
| 82 |
+
task = gr.Dropdown(["Sentiment Analysis", "Summarization", "Text-to-Speech"], value="Sentiment Analysis")
|
| 83 |
+
input_text = gr.Textbox(lines=6, label="Input")
|
| 84 |
+
run_btn = gr.Button("Run")
|
| 85 |
+
output = gr.Textbox(label="Result")
|
| 86 |
+
audio = gr.Audio(type="filepath", visible=False)
|
| 87 |
+
|
| 88 |
+
run_btn.click(perform_task, [task, input_text], [output, audio, audio])
|
| 89 |
+
|
| 90 |
+
with gr.Tab("Chatbot"):
|
| 91 |
+
model_select = gr.Dropdown(["gpt-3.5-turbo", "gpt-4"], value="gpt-3.5-turbo", label="Model")
|
| 92 |
+
system_prompt = gr.Textbox(label="System Prompt", placeholder="You are a helpful assistant...")
|
| 93 |
+
chat_ui = gr.Chatbot(label="Chat", height=400)
|
| 94 |
+
message_input = gr.Textbox(placeholder="Type your message...")
|
| 95 |
+
send_btn = gr.Button("Send")
|
| 96 |
+
clear_btn = gr.Button("Clear")
|
| 97 |
+
|
| 98 |
+
model_select.change(chatbot.set_model, inputs=[model_select], outputs=[])
|
| 99 |
+
|
| 100 |
+
def handle_chat(msg, hist, sys_prompt):
|
| 101 |
+
return chatbot.stream_chat(msg, hist, sys_prompt)
|
| 102 |
+
|
| 103 |
+
send_btn.click(handle_chat, [message_input, chat_ui, system_prompt], [chat_ui])
|
| 104 |
+
message_input.submit(handle_chat, [message_input, chat_ui, system_prompt], [chat_ui])
|
| 105 |
+
clear_btn.click(lambda: [], outputs=[chat_ui])
|
| 106 |
|
| 107 |
+
demo.launch(share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|