Spaces:
Sleeping
Sleeping
martinpalinkov
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,135 +1,133 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
import
|
7 |
-
import
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
model
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
image =
|
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 |
-
chat_history_ids =
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
bot_response += f"
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
tts
|
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 |
-
if __name__ == "__main__":
|
135 |
-
demo.launch(share=True)
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, MarianMTModel, MarianTokenizer, BlipProcessor, BlipForConditionalGeneration
|
3 |
+
from gtts import gTTS
|
4 |
+
import torch
|
5 |
+
import logging
|
6 |
+
import traceback
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
+
logging.basicConfig(filename="error_log.txt", level=logging.ERROR, format="%(asctime)s - %(message)s")
|
10 |
+
|
11 |
+
chatbot_model_name = "microsoft/DialoGPT-medium"
|
12 |
+
tokenizer = AutoTokenizer.from_pretrained(chatbot_model_name)
|
13 |
+
chatbot_model = AutoModelForCausalLM.from_pretrained(chatbot_model_name)
|
14 |
+
|
15 |
+
blip_model_name = "Salesforce/blip-image-captioning-base"
|
16 |
+
blip_processor = BlipProcessor.from_pretrained(blip_model_name)
|
17 |
+
blip_model = BlipForConditionalGeneration.from_pretrained(blip_model_name)
|
18 |
+
|
19 |
+
def get_translation_model(src_lang, tgt_lang):
|
20 |
+
model_name = f'Helsinki-NLP/opus-mt-{src_lang}-{tgt_lang}'
|
21 |
+
model = MarianMTModel.from_pretrained(model_name)
|
22 |
+
tokenizer = MarianTokenizer.from_pretrained(model_name)
|
23 |
+
return model, tokenizer
|
24 |
+
|
25 |
+
chat_history_ids = None
|
26 |
+
MAX_LENGTH = 1024
|
27 |
+
MAX_HISTORY_LENGTH = 5
|
28 |
+
|
29 |
+
def generate_image_caption(image_path):
|
30 |
+
try:
|
31 |
+
image = Image.open(image_path)
|
32 |
+
image.show()
|
33 |
+
image = blip_processor(images=image, return_tensors="pt").pixel_values
|
34 |
+
with torch.no_grad():
|
35 |
+
caption = blip_model.generate(image, max_length=50, num_beams=5)
|
36 |
+
return blip_processor.decode(caption[0], skip_special_tokens=True)
|
37 |
+
except Exception as e:
|
38 |
+
logging.error(f"Error in BLIP image captioning: {str(e)}\n{traceback.format_exc()}")
|
39 |
+
return "Error processing image."
|
40 |
+
|
41 |
+
def chatbot_with_image(message, language, image_path=None, reset=False):
|
42 |
+
global chat_history_ids
|
43 |
+
|
44 |
+
if reset:
|
45 |
+
chat_history_ids = None
|
46 |
+
return "Chat history reset.", None
|
47 |
+
|
48 |
+
if not message.strip() and not image_path:
|
49 |
+
return "Please enter a message or upload an image.", None
|
50 |
+
|
51 |
+
bot_response = ""
|
52 |
+
|
53 |
+
try:
|
54 |
+
if message.strip():
|
55 |
+
new_user_input_ids = tokenizer.encode(message + tokenizer.eos_token, return_tensors="pt")
|
56 |
+
if chat_history_ids is not None:
|
57 |
+
chat_history_ids = torch.cat([chat_history_ids, new_user_input_ids], dim=-1)
|
58 |
+
else:
|
59 |
+
chat_history_ids = new_user_input_ids
|
60 |
+
|
61 |
+
if chat_history_ids.shape[-1] > MAX_HISTORY_LENGTH * MAX_LENGTH:
|
62 |
+
chat_history_ids = chat_history_ids[:, -MAX_HISTORY_LENGTH * MAX_LENGTH:]
|
63 |
+
|
64 |
+
bot_input_ids = chat_history_ids
|
65 |
+
chat_history_ids = chatbot_model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)
|
66 |
+
bot_response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
|
67 |
+
except Exception as e:
|
68 |
+
bot_response = f"Error processing message: {str(e)}"
|
69 |
+
logging.error(f"Error in chatbot response generation: {str(e)}\n{traceback.format_exc()}")
|
70 |
+
|
71 |
+
if image_path:
|
72 |
+
try:
|
73 |
+
image_caption = generate_image_caption(image_path)
|
74 |
+
bot_response += f"The image shows: {image_caption}."
|
75 |
+
except Exception as e:
|
76 |
+
bot_response += f" Error processing image: {str(e)}"
|
77 |
+
logging.error(f"Error in image processing: {str(e)}\n{traceback.format_exc()}")
|
78 |
+
|
79 |
+
try:
|
80 |
+
if language != "en":
|
81 |
+
translation_model, translation_tokenizer = get_translation_model("en", language)
|
82 |
+
translated = translation_model.generate(**translation_tokenizer(bot_response, return_tensors="pt", padding=True, truncation=True))
|
83 |
+
bot_response = translation_tokenizer.decode(translated[0], skip_special_tokens=True)
|
84 |
+
except Exception as e:
|
85 |
+
bot_response += f" Error in translation: {str(e)}"
|
86 |
+
logging.error(f"Error in translation: {str(e)}\n{traceback.format_exc()}")
|
87 |
+
|
88 |
+
try:
|
89 |
+
tts = gTTS(bot_response, lang=language)
|
90 |
+
audio_path = "response.mp3"
|
91 |
+
tts.save(audio_path)
|
92 |
+
except Exception as e:
|
93 |
+
bot_response += f" Error generating TTS: {str(e)}"
|
94 |
+
logging.error(f"Error in TTS generation: {str(e)}\n{traceback.format_exc()}")
|
95 |
+
audio_path = None
|
96 |
+
|
97 |
+
return bot_response, audio_path
|
98 |
+
|
99 |
+
with gr.Blocks() as demo:
|
100 |
+
with gr.Row():
|
101 |
+
gr.Markdown("### Chatbot with Image Understanding and Language Support")
|
102 |
+
|
103 |
+
with gr.Row():
|
104 |
+
output_audio = gr.Audio(label="Generated Speech", type="filepath")
|
105 |
+
output_text = gr.Textbox(label="Bot Response")
|
106 |
+
|
107 |
+
language_dropdown = gr.Dropdown(
|
108 |
+
choices=["en", "es", "fr", "de", "it", "zh", "pl"],
|
109 |
+
label="Select Language",
|
110 |
+
value="en"
|
111 |
+
)
|
112 |
+
image_input = gr.Image(label="Upload Image", type="filepath")
|
113 |
+
text_input = gr.Textbox(label="Your Message", placeholder="Type your message here...")
|
114 |
+
|
115 |
+
with gr.Row():
|
116 |
+
send_button = gr.Button("Send")
|
117 |
+
reset_button = gr.Button("Reset Chat")
|
118 |
+
|
119 |
+
|
120 |
+
send_button.click(
|
121 |
+
chatbot_with_image,
|
122 |
+
inputs=[text_input, language_dropdown, image_input, gr.State(False)],
|
123 |
+
outputs=[output_text, output_audio]
|
124 |
+
)
|
125 |
+
|
126 |
+
reset_button.click(
|
127 |
+
fn=lambda reset: ("Chat history reset.", None) if reset else ("", None),
|
128 |
+
inputs=[gr.State(True)],
|
129 |
+
outputs=[output_text, output_audio]
|
130 |
+
)
|
131 |
+
|
132 |
+
if __name__ == "__main__":
|
133 |
+
demo.launch(share=True)
|
|
|
|