sagar007 commited on
Commit
106d95c
·
verified ·
1 Parent(s): 2553fb1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -21
app.py CHANGED
@@ -4,16 +4,16 @@ from transformers import pipeline, WhisperProcessor, WhisperForConditionalGenera
4
  from gtts import gTTS
5
  import gradio as gr
6
  from PIL import Image
7
- import subprocess
8
-
9
- # Import and initialize ZeroGPU
10
  import spaces
11
- spaces.init()
12
 
13
- print("Using GPU for operations when available")
 
 
14
 
15
- # Install flash-attn
16
- subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
17
 
18
  # Function to safely load pipeline
19
  @spaces.GPU
@@ -21,7 +21,7 @@ def load_pipeline(model_name, **kwargs):
21
  try:
22
  return pipeline(model=model_name, device=0, **kwargs)
23
  except Exception as e:
24
- print(f"Error loading {model_name} pipeline: {e}")
25
  return None
26
 
27
  # Load Whisper model for speech recognition
@@ -32,7 +32,7 @@ def load_whisper():
32
  model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-small").cuda()
33
  return processor, model
34
  except Exception as e:
35
- print(f"Error loading Whisper model: {e}")
36
  return None, None
37
 
38
  # Load sarvam-2b for text generation
@@ -43,10 +43,14 @@ def load_sarvam():
43
  # Load vision model
44
  @spaces.GPU
45
  def load_vision_model():
46
- model_id = "microsoft/Phi-3.5-vision-instruct"
47
- model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True, torch_dtype="auto", attn_implementation="flash_attention_2").cuda().eval()
48
- processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
49
- return model, processor
 
 
 
 
50
 
51
  # Process audio input
52
  @spaces.GPU
@@ -61,7 +65,8 @@ def process_audio_input(audio, whisper_processor, whisper_model):
61
  transcription = whisper_processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
62
  return transcription
63
  except Exception as e:
64
- return f"Error processing audio: {str(e)}. Please type your message instead."
 
65
 
66
  # Generate response
67
  def text_to_speech(text, lang='hi'):
@@ -72,10 +77,11 @@ def text_to_speech(text, lang='hi'):
72
  else:
73
  tts = gTTS(text=text, lang=lang)
74
 
75
- tts.save("response.mp3")
76
- return "response.mp3"
 
77
  except Exception as e:
78
- print(f"Error in text-to-speech: {str(e)}")
79
  return None
80
 
81
  # Detect language (placeholder function, replace with actual implementation)
@@ -93,10 +99,14 @@ def generate_response(transcription, sarvam_pipe):
93
  response = sarvam_pipe(transcription, max_length=100, num_return_sequences=1)[0]['generated_text']
94
  return response
95
  except Exception as e:
96
- return f"Error generating response: {str(e)}"
 
97
 
98
  @spaces.GPU
99
  def process_image(image, text_input, vision_model, vision_processor):
 
 
 
100
  try:
101
  prompt = f"<|user|>\n<|image_1|>\n{text_input}<|end|>\n<|assistant|>\n"
102
  image = Image.fromarray(image).convert("RGB")
@@ -106,7 +116,8 @@ def process_image(image, text_input, vision_model, vision_processor):
106
  response = vision_processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
107
  return response
108
  except Exception as e:
109
- return f"Error processing image: {str(e)}"
 
110
 
111
  @spaces.GPU
112
  def multimodal_assistant(input_type, audio_input, text_input, image_input):
@@ -131,8 +142,8 @@ def multimodal_assistant(input_type, audio_input, text_input, image_input):
131
 
132
  return response, audio_response
133
  except Exception as e:
134
- error_message = f"An error occurred: {str(e)}"
135
- return error_message, None
136
 
137
  # Custom CSS (you can keep your existing custom CSS here)
138
  custom_css = """
 
4
  from gtts import gTTS
5
  import gradio as gr
6
  from PIL import Image
7
+ import logging
8
+ import os
 
9
  import spaces
 
10
 
11
+ # Set up logging
12
+ logging.basicConfig(level=logging.INFO)
13
+ logger = logging.getLogger(__name__)
14
 
15
+ # Initialize ZeroGPU
16
+ spaces.init()
17
 
18
  # Function to safely load pipeline
19
  @spaces.GPU
 
21
  try:
22
  return pipeline(model=model_name, device=0, **kwargs)
23
  except Exception as e:
24
+ logger.error(f"Error loading {model_name} pipeline: {e}")
25
  return None
26
 
27
  # Load Whisper model for speech recognition
 
32
  model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-small").cuda()
33
  return processor, model
34
  except Exception as e:
35
+ logger.error(f"Error loading Whisper model: {e}")
36
  return None, None
37
 
38
  # Load sarvam-2b for text generation
 
43
  # Load vision model
44
  @spaces.GPU
45
  def load_vision_model():
46
+ try:
47
+ model_id = "microsoft/Phi-3.5-vision-instruct"
48
+ model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True, torch_dtype="auto", attn_implementation="flash_attention_2").cuda().eval()
49
+ processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
50
+ return model, processor
51
+ except Exception as e:
52
+ logger.error(f"Error loading vision model: {e}")
53
+ return None, None
54
 
55
  # Process audio input
56
  @spaces.GPU
 
65
  transcription = whisper_processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
66
  return transcription
67
  except Exception as e:
68
+ logger.error(f"Error processing audio: {e}")
69
+ return f"Error processing audio. Please type your message instead."
70
 
71
  # Generate response
72
  def text_to_speech(text, lang='hi'):
 
77
  else:
78
  tts = gTTS(text=text, lang=lang)
79
 
80
+ output_path = "/tmp/response.mp3"
81
+ tts.save(output_path)
82
+ return output_path
83
  except Exception as e:
84
+ logger.error(f"Error in text-to-speech: {e}")
85
  return None
86
 
87
  # Detect language (placeholder function, replace with actual implementation)
 
99
  response = sarvam_pipe(transcription, max_length=100, num_return_sequences=1)[0]['generated_text']
100
  return response
101
  except Exception as e:
102
+ logger.error(f"Error generating response: {e}")
103
+ return f"Error generating response. Please try again."
104
 
105
  @spaces.GPU
106
  def process_image(image, text_input, vision_model, vision_processor):
107
+ if vision_model is None or vision_processor is None:
108
+ return "Error: Vision model is not available."
109
+
110
  try:
111
  prompt = f"<|user|>\n<|image_1|>\n{text_input}<|end|>\n<|assistant|>\n"
112
  image = Image.fromarray(image).convert("RGB")
 
116
  response = vision_processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
117
  return response
118
  except Exception as e:
119
+ logger.error(f"Error processing image: {e}")
120
+ return f"Error processing image. Please try again."
121
 
122
  @spaces.GPU
123
  def multimodal_assistant(input_type, audio_input, text_input, image_input):
 
142
 
143
  return response, audio_response
144
  except Exception as e:
145
+ logger.error(f"An error occurred in multimodal_assistant: {e}")
146
+ return f"An error occurred. Please try again.", None
147
 
148
  # Custom CSS (you can keep your existing custom CSS here)
149
  custom_css = """