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