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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 3 |
+
from diffusers import StableDiffusionPipeline
|
| 4 |
+
import torch
|
| 5 |
+
import os
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
# Set up logging
|
| 9 |
+
logging.basicConfig(level=logging.INFO)
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
# Read the Hugging Face access token from the environment variable
|
| 13 |
+
read_token = os.getenv('AccToken')
|
| 14 |
+
if not read_token:
|
| 15 |
+
raise ValueError("Hugging Face access token not found. Please set the AccToken environment variable.")
|
| 16 |
+
from huggingface_hub import login
|
| 17 |
+
login(read_token)
|
| 18 |
+
|
| 19 |
+
# Set device to GPU if available
|
| 20 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 21 |
+
logger.info(f"Device set to use {device}")
|
| 22 |
+
|
| 23 |
+
# Define a dictionary of conversational models
|
| 24 |
+
conversational_models = {
|
| 25 |
+
"Qwen": "Qwen/QwQ-32B",
|
| 26 |
+
"DeepSeek R1": "deepseek-ai/DeepSeek-R1",
|
| 27 |
+
"Perplexity (R1 Post-trained)": "perplexity-ai/r1-1776",
|
| 28 |
+
"Llama-Instruct by Meta": "meta-llama/Llama-3.2-3B-Instruct",
|
| 29 |
+
"Mistral": "mistralai/Mistral-7B-v0.1",
|
| 30 |
+
"Gemma": "google/gemma-2-2b-it",
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
# Define a dictionary of Text-to-Image models
|
| 34 |
+
text_to_image_models = {
|
| 35 |
+
"Stable Diffusion 3.5 Large": "stabilityai/stable-diffusion-3.5-large",
|
| 36 |
+
"Stable Diffusion 1.4": "CompVis/stable-diffusion-v1-4",
|
| 37 |
+
"Flux Dev": "black-forest-labs/FLUX.1-dev",
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
# Define a dictionary of Text-to-Speech models
|
| 41 |
+
text_to_speech_models = {
|
| 42 |
+
"Spark TTS": "SparkAudio/Spark-TTS-0.5B",
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
# Initialize tokenizers and models for conversational AI
|
| 46 |
+
conversational_tokenizers = {}
|
| 47 |
+
conversational_models_loaded = {}
|
| 48 |
+
|
| 49 |
+
# Initialize pipelines for Text-to-Image
|
| 50 |
+
text_to_image_pipelines = {}
|
| 51 |
+
|
| 52 |
+
# Initialize pipelines for Text-to-Speech
|
| 53 |
+
text_to_speech_pipelines = {}
|
| 54 |
+
|
| 55 |
+
# Initialize pipelines for other tasks
|
| 56 |
+
visual_qa_pipeline = pipeline("visual-question-answering", model="dandelin/vilt-b32-finetuned-vqa", device=device)
|
| 57 |
+
document_qa_pipeline = pipeline("question-answering", model="deepset/roberta-base-squad2", device=device)
|
| 58 |
+
image_classification_pipeline = pipeline("image-classification", model="facebook/deit-base-distilled-patch16-224", device=device)
|
| 59 |
+
object_detection_pipeline = pipeline("object-detection", model="facebook/detr-resnet-50", device=device)
|
| 60 |
+
video_classification_pipeline = pipeline("video-classification", model="facebook/timesformer-base-finetuned-k400", device=device)
|
| 61 |
+
summarization_pipeline = pipeline("summarization", model="facebook/bart-large-cnn", device=device)
|
| 62 |
+
|
| 63 |
+
# Load speaker embeddings for text-to-audio
|
| 64 |
+
def load_speaker_embeddings(model_name):
|
| 65 |
+
if model_name == "microsoft/speecht5_tts":
|
| 66 |
+
logger.info("Loading speaker embeddings for SpeechT5")
|
| 67 |
+
from datasets import load_dataset
|
| 68 |
+
dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
|
| 69 |
+
speaker_embeddings = torch.tensor(dataset[7306]["xvector"]).unsqueeze(0).to(device) # Example speaker
|
| 70 |
+
return speaker_embeddings
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
# Use a different model for text-to-audio if stabilityai/stable-audio-open-1.0 is not supported
|
| 74 |
+
try:
|
| 75 |
+
text_to_audio_pipeline = pipeline("text-to-audio", model="stabilityai/stable-audio-open-1.0", device=device)
|
| 76 |
+
except ValueError as e:
|
| 77 |
+
logger.error(f"Error loading stabilityai/stable-audio-open-1.0: {e}")
|
| 78 |
+
logger.info("Falling back to a different text-to-audio model.")
|
| 79 |
+
text_to_audio_pipeline = pipeline("text-to-audio", model="microsoft/speecht5_tts", device=device)
|
| 80 |
+
speaker_embeddings = load_speaker_embeddings("microsoft/speecht5_tts")
|
| 81 |
+
|
| 82 |
+
audio_classification_pipeline = pipeline("audio-classification", model="facebook/wav2vec2-base", device=device)
|
| 83 |
+
|
| 84 |
+
def load_conversational_model(model_name):
|
| 85 |
+
if model_name not in conversational_models_loaded:
|
| 86 |
+
logger.info(f"Loading conversational model: {model_name}")
|
| 87 |
+
tokenizer = AutoTokenizer.from_pretrained(conversational_models[model_name], use_auth_token=read_token)
|
| 88 |
+
model = AutoModelForCausalLM.from_pretrained(conversational_models[model_name], use_auth_token=read_token).to(device)
|
| 89 |
+
conversational_tokenizers[model_name] = tokenizer
|
| 90 |
+
conversational_models_loaded[model_name] = model
|
| 91 |
+
return conversational_tokenizers[model_name], conversational_models_loaded[model_name]
|
| 92 |
+
|
| 93 |
+
def chat(model_name, user_input, history=[]):
|
| 94 |
+
tokenizer, model = load_conversational_model(model_name)
|
| 95 |
+
|
| 96 |
+
# Encode the input
|
| 97 |
+
input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors="pt").to(device)
|
| 98 |
+
|
| 99 |
+
# Generate a response
|
| 100 |
+
with torch.no_grad():
|
| 101 |
+
output = model.generate(input_ids, max_length=150, pad_token_id=tokenizer.eos_token_id)
|
| 102 |
+
|
| 103 |
+
response = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 104 |
+
|
| 105 |
+
# Clean up the response to remove the user input part
|
| 106 |
+
response = response[len(user_input):].strip()
|
| 107 |
+
|
| 108 |
+
# Append to chat history
|
| 109 |
+
history.append((user_input, response))
|
| 110 |
+
|
| 111 |
+
return history, history
|
| 112 |
+
|
| 113 |
+
def generate_image(model_name, prompt):
|
| 114 |
+
if model_name not in text_to_image_pipelines:
|
| 115 |
+
logger.info(f"Loading text-to-image model: {model_name}")
|
| 116 |
+
text_to_image_pipelines[model_name] = StableDiffusionPipeline.from_pretrained(
|
| 117 |
+
text_to_image_models[model_name], use_auth_token=read_token, torch_dtype=torch.float16, device_map="auto"
|
| 118 |
+
)
|
| 119 |
+
pipeline = text_to_image_pipelines[model_name]
|
| 120 |
+
image = pipeline(prompt).images[0]
|
| 121 |
+
return image
|
| 122 |
+
|
| 123 |
+
def generate_speech(model_name, text):
|
| 124 |
+
if model_name not in text_to_speech_pipelines:
|
| 125 |
+
logger.info(f"Loading text-to-speech model: {model_name}")
|
| 126 |
+
text_to_speech_pipelines[model_name] = pipeline(
|
| 127 |
+
"text-to-speech", model=text_to_speech_models[model_name], use_auth_token=read_token, device=device
|
| 128 |
+
)
|
| 129 |
+
pipeline = text_to_speech_pipelines[model_name]
|
| 130 |
+
audio = pipeline(text, speaker_embeddings=speaker_embeddings)
|
| 131 |
+
return audio["audio"]
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def visual_qa(image, question):
|
| 136 |
+
result = visual_qa_pipeline(image, question)
|
| 137 |
+
return result["answer"]
|
| 138 |
+
|
| 139 |
+
def document_qa(document, question):
|
| 140 |
+
result = document_qa_pipeline(question=question, context=document)
|
| 141 |
+
return result["answer"]
|
| 142 |
+
|
| 143 |
+
def image_classification(image):
|
| 144 |
+
result = image_classification_pipeline(image)
|
| 145 |
+
return result
|
| 146 |
+
|
| 147 |
+
def object_detection(image):
|
| 148 |
+
result = object_detection_pipeline(image)
|
| 149 |
+
return result
|
| 150 |
+
|
| 151 |
+
def video_classification(video):
|
| 152 |
+
result = video_classification_pipeline(video)
|
| 153 |
+
return result
|
| 154 |
+
|
| 155 |
+
def summarize_text(text):
|
| 156 |
+
result = summarization_pipeline(text)
|
| 157 |
+
return result[0]["summary_text"]
|
| 158 |
+
|
| 159 |
+
def text_to_audio(text):
|
| 160 |
+
global speaker_embeddings
|
| 161 |
+
result = text_to_audio_pipeline(text, speaker_embeddings=speaker_embeddings)
|
| 162 |
+
return result["audio"]
|
| 163 |
+
|
| 164 |
+
def audio_classification(audio):
|
| 165 |
+
result = audio_classification_pipeline(audio)
|
| 166 |
+
return result
|
| 167 |
+
|
| 168 |
+
# Define the Gradio interface
|
| 169 |
+
with gr.Blocks() as demo:
|
| 170 |
+
gr.Markdown("## Versatile AI Chatbot and Text-to-X Tasks")
|
| 171 |
+
|
| 172 |
+
with gr.Tab("Conversational AI"):
|
| 173 |
+
conversational_model_choice = gr.Dropdown(list(conversational_models.keys()), label="Choose a Conversational Model")
|
| 174 |
+
conversational_chatbot = gr.Chatbot(label="Chat")
|
| 175 |
+
conversational_message = gr.Textbox(label="Message")
|
| 176 |
+
conversational_submit = gr.Button("Submit")
|
| 177 |
+
|
| 178 |
+
conversational_submit.click(chat, inputs=[conversational_model_choice, conversational_message, conversational_chatbot], outputs=[conversational_chatbot, conversational_chatbot])
|
| 179 |
+
conversational_message.submit(chat, inputs=[conversational_model_choice, conversational_message, conversational_chatbot], outputs=[conversational_chatbot, conversational_chatbot])
|
| 180 |
+
|
| 181 |
+
with gr.Tab("Text-to-Image"):
|
| 182 |
+
text_to_image_model_choice = gr.Dropdown(list(text_to_image_models.keys()), label="Choose a Text-to-Image Model")
|
| 183 |
+
text_to_image_prompt = gr.Textbox(label="Prompt")
|
| 184 |
+
text_to_image_generate = gr.Button("Generate Image")
|
| 185 |
+
text_to_image_output = gr.Image(label="Generated Image")
|
| 186 |
+
|
| 187 |
+
text_to_image_generate.click(generate_image, inputs=[text_to_image_model_choice, text_to_image_prompt], outputs=text_to_image_output)
|
| 188 |
+
|
| 189 |
+
with gr.Tab("Text-to-Speech"):
|
| 190 |
+
text_to_speech_model_choice = gr.Dropdown(list(text_to_speech_models.keys()), label="Choose a Text-to-Speech Model")
|
| 191 |
+
text_to_speech_text = gr.Textbox(label="Text")
|
| 192 |
+
text_to_speech_generate = gr.Button("Generate Speech")
|
| 193 |
+
text_to_speech_output = gr.Audio(label="Generated Speech")
|
| 194 |
+
|
| 195 |
+
text_to_speech_generate.click(generate_speech, inputs=[text_to_speech_model_choice, text_to_speech_text], outputs=text_to_speech_output)
|
| 196 |
+
|
| 197 |
+
with gr.Tab("Visual Question Answering"):
|
| 198 |
+
visual_qa_image = gr.Image(label="Upload Image")
|
| 199 |
+
visual_qa_question = gr.Textbox(label="Question")
|
| 200 |
+
visual_qa_generate = gr.Button("Answer")
|
| 201 |
+
visual_qa_output = gr.Textbox(label="Answer")
|
| 202 |
+
|
| 203 |
+
visual_qa_generate.click(visual_qa, inputs=[visual_qa_image, visual_qa_question], outputs=visual_qa_output)
|
| 204 |
+
|
| 205 |
+
with gr.Tab("Document Question Answering"):
|
| 206 |
+
document_qa_document = gr.Textbox(label="Document Text")
|
| 207 |
+
document_qa_question = gr.Textbox(label="Question")
|
| 208 |
+
document_qa_generate = gr.Button("Answer")
|
| 209 |
+
document_qa_output = gr.Textbox(label="Answer")
|
| 210 |
+
|
| 211 |
+
document_qa_generate.click(document_qa, inputs=[document_qa_document, document_qa_question], outputs=document_qa_output)
|
| 212 |
+
|
| 213 |
+
with gr.Tab("Image Classification"):
|
| 214 |
+
image_classification_image = gr.Image(label="Upload Image")
|
| 215 |
+
image_classification_generate = gr.Button("Classify")
|
| 216 |
+
image_classification_output = gr.Textbox(label="Classification Result")
|
| 217 |
+
|
| 218 |
+
image_classification_generate.click(image_classification, inputs=image_classification_image, outputs=image_classification_output)
|
| 219 |
+
|
| 220 |
+
with gr.Tab("Object Detection"):
|
| 221 |
+
object_detection_image = gr.Image(label="Upload Image")
|
| 222 |
+
object_detection_generate = gr.Button("Detect")
|
| 223 |
+
object_detection_output = gr.Image(label="Detection Result")
|
| 224 |
+
|
| 225 |
+
object_detection_generate.click(object_detection, inputs=object_detection_image, outputs=object_detection_output)
|
| 226 |
+
|
| 227 |
+
with gr.Tab("Video Classification"):
|
| 228 |
+
video_classification_video = gr.Video(label="Upload Video")
|
| 229 |
+
video_classification_generate = gr.Button("Classify")
|
| 230 |
+
video_classification_output = gr.Textbox(label="Classification Result")
|
| 231 |
+
|
| 232 |
+
video_classification_generate.click(video_classification, inputs=video_classification_video, outputs=video_classification_output)
|
| 233 |
+
|
| 234 |
+
with gr.Tab("Summarization"):
|
| 235 |
+
summarize_text_text = gr.Textbox(label="Text")
|
| 236 |
+
summarize_text_generate = gr.Button("Summarize")
|
| 237 |
+
summarize_text_output = gr.Textbox(label="Summary")
|
| 238 |
+
|
| 239 |
+
summarize_text_generate.click(summarize_text, inputs=summarize_text_text, outputs=summarize_text_output)
|
| 240 |
+
|
| 241 |
+
with gr.Tab("Text-to-Audio"):
|
| 242 |
+
text_to_audio_text = gr.Textbox(label="Text")
|
| 243 |
+
text_to_audio_generate = gr.Button("Generate Audio")
|
| 244 |
+
text_to_audio_output = gr.Audio(label="Generated Audio")
|
| 245 |
+
|
| 246 |
+
text_to_audio_generate.click(text_to_audio, inputs=text_to_audio_text, outputs=text_to_audio_output)
|
| 247 |
+
|
| 248 |
+
with gr.Tab("Audio Classification"):
|
| 249 |
+
audio_classification_audio = gr.Audio(label="Upload Audio")
|
| 250 |
+
audio_classification_generate = gr.Button("Classify")
|
| 251 |
+
audio_classification_output = gr.Textbox(label="Classification Result")
|
| 252 |
+
|
| 253 |
+
audio_classification_generate.click(audio_classification, inputs=audio_classification_audio, outputs=audio_classification_output)
|
| 254 |
+
|
| 255 |
+
# Launch the Gradio interface
|
| 256 |
+
demo.launch()
|