Yasser18 commited on
Commit
311fe9c
Β·
verified Β·
1 Parent(s): fe8c737

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +217 -165
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
- # Load models
8
- sentiment_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  summarization_pipeline = pipeline("summarization", model="RussianNLP/FRED-T5-Summarizer")
10
 
11
- # Task logic
12
- def perform_task(task, text):
13
  if not text.strip():
14
- return "⚠️ Please enter some text to analyze.", None, gr.update(visible=False)
15
-
16
- time.sleep(0.5)
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
- elif task == "Text-to-Speech":
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 "⚠️ Please enter some text to get started!", None, gr.update(visible=False)
76
- result_text, audio_file, audio_update = perform_task(task, text)
77
- return result_text, audio_file, audio_update
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
- # UI Layout
89
- with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
90
- gr.HTML(custom_css)
91
- gr.Markdown("# πŸ€– Multi-Task AI Assistant", elem_id="title")
92
-
93
- with gr.Tabs():
94
- # === Main Assistant Tab ===
95
- with gr.Tab("🧠 Multi-Task Interface"):
96
- gr.Markdown("""
97
- <div style="text-align: center; margin-bottom: 2rem; color: #b0b0b0; font-size: 1.2rem;">
98
- Harness the power of AI for <strong>sentiment analysis</strong>, <strong>text summarization</strong>, and <strong>text-to-speech</strong> conversion
99
- </div>
100
- """)
101
-
102
- with gr.Row():
103
- with gr.Column(scale=1, min_width=250):
104
- task_selector = gr.Dropdown(
105
- choices=["Sentiment Analysis", "Summarization", "Text-to-Speech"],
106
- label="πŸ”§ Select AI Task",
107
- value="Sentiment Analysis",
108
- info="Choose the AI capability you want to use"
 
 
 
 
109
  )
110
-
111
- gr.Markdown("""
112
- **πŸ“Š Sentiment Analysis**: Analyze emotional tone and polarity of text
113
- **βœ‚οΈ Summarization**: Generate concise summaries of long text
114
- **πŸ”Š Text-to-Speech**: Convert text into natural-sounding audio
115
- """, elem_classes=["task-info"])
116
-
117
- with gr.Column(scale=2):
118
- textbox = gr.Textbox(
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
- with gr.Row():
126
- run_button = gr.Button("πŸš€ Process with AI", size="lg", variant="primary")
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
- with gr.Column(scale=1):
139
- output_audio = gr.Audio(
140
- label="πŸ”Š Generated Audio",
141
- type="filepath",
142
- visible=False,
 
 
143
  )
144
-
145
- run_button.click(
146
- fn=handle_task_processing,
147
- inputs=[task_selector, textbox],
148
- outputs=[output_text, output_audio, output_audio]
149
- )
150
-
151
- # === Sentiment Chatbot Tab ===
152
- with gr.Tab("πŸ’¬ Sentiment Chatbot"):
153
- gr.ChatInterface(
154
- fn=lambda message, history: (
155
- history + [
156
- (
157
- message,
158
- f"🧠 Sentiment: {sentiment_pipeline(message)[0]['label']} (Confidence: {round(sentiment_pipeline(message)[0]['score'], 2)})"
159
  )
160
- ],
161
- history + [
162
- (
163
- message,
164
- f"🧠 Sentiment: {sentiment_pipeline(message)[0]['label']} (Confidence: {round(sentiment_pipeline(message)[0]['score'], 2)})"
 
 
165
  )
166
- ]
167
- ),
168
- title="Sentiment Chatbot",
169
- description="Chat with the AI to detect the sentiment of your messages.",
170
- )
171
-
172
- gr.Markdown("""
173
- <div style="text-align: center; margin-top: 3rem; padding: 2rem; color: #666; border-top: 1px solid #333;">
174
- <p>✨ <strong>Multi-Task AI Assistant</strong> - Powered by Transformers & Gradio</p>
175
- <p>Built with ❀️ for seamless AI interaction</p>
176
- </div>
177
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
- # Launch
180
  if __name__ == "__main__":
181
- demo.launch(
182
- share=True,
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)