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