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