SharathReddy commited on
Commit
3554051
·
verified ·
1 Parent(s): bd61cc4

Upload 2 files

Browse files
Files changed (3) hide show
  1. .gitattributes +1 -0
  2. app.py +105 -91
  3. img.png +3 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ img.png filter=lfs diff=lfs merge=lfs -text
app.py CHANGED
@@ -1,129 +1,143 @@
1
- # app.py
2
  import torch
3
- from transformers import BitsAndBytesConfig, pipeline
4
  import whisper
5
  import gradio as gr
6
- import warnings
7
- import os
8
  from gtts import gTTS
9
  from PIL import Image
10
  import nltk
11
- from nltk import sent_tokenize
12
  import re
13
- import datetime
 
 
14
 
15
- # Download required NLTK data
16
- nltk.download('punkt')
17
- nltk.download('punkt_tab')
18
 
19
- # Configure model settings
20
- quantization_config = BitsAndBytesConfig(
21
- load_in_4bit=True,
22
- bnb_4bit_compute_dtype=torch.float16
23
- )
24
 
25
- # Initialize models
26
- model_id = "llava-hf/llava-1.5-7b-hf"
27
- pipe = pipeline("image-to-text",
28
- model=model_id,
29
- model_kwargs={"quantization_config": quantization_config})
30
-
31
- # Load Whisper model
32
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
33
- model = whisper.load_model("medium", device=DEVICE)
34
-
35
- # Setup logging
36
- def setup_logging():
37
- tstamp = datetime.datetime.now()
38
- tstamp = str(tstamp).replace(' ','_')
39
- logfile = f'logs/{tstamp}_log.txt'
40
- os.makedirs('logs', exist_ok=True)
41
- return logfile
 
 
 
 
 
 
 
 
 
 
42
 
43
- logfile = setup_logging()
44
-
45
- def writehistory(text):
46
- with open(logfile, 'a', encoding='utf-8') as f:
47
- f.write(text)
48
- f.write('\n')
49
-
50
- # Core functions
51
  def img2txt(input_text, input_image):
52
- image = Image.open(input_image)
 
 
 
53
 
54
- if type(input_text) == tuple:
55
- prompt_instructions = """
56
- Describe the image using as much detail as possible, is it a painting,
57
- a photograph, what colors are predominant, what is the image about?
58
- """
59
- else:
60
- prompt_instructions = f"""
61
- Act as an expert in imagery descriptive analysis, using as much detail
62
- as possible from the image, respond to the following prompt: {input_text}
63
- """
64
-
65
- prompt = f"USER: <image>\n{prompt_instructions}\nASSISTANT:"
66
- outputs = pipe(image, prompt=prompt, generate_kwargs={"max_new_tokens": 200})
67
-
68
- if outputs and outputs[0]["generated_text"]:
69
- match = re.search(r'ASSISTANT:\s*(.*)', outputs[0]["generated_text"])
70
- reply = match.group(1) if match else "No response found."
71
- else:
72
- reply = "No response generated."
73
-
74
- return reply
75
 
76
  def transcribe(audio):
77
- if not audio:
 
 
 
 
 
78
  return ''
79
 
80
- audio = whisper.load_audio(audio)
81
- audio = whisper.pad_or_trim(audio)
82
- mel = whisper.log_mel_spectrogram(audio).to(model.device)
83
- options = whisper.DecodingOptions()
84
- result = whisper.decode(model, mel, options)
85
- return result.text
86
-
87
- def text_to_speech(text, file_path="output.mp3"):
88
- tts = gTTS(text=text, lang='en', slow=False)
89
- tts.save(file_path)
90
- return file_path
91
 
92
- def process_inputs(audio_path, image_path):
 
93
  try:
94
- speech_to_text_output = transcribe(audio_path)
95
- writehistory(f"Speech to text: {speech_to_text_output}")
 
 
 
 
 
96
 
97
- if image_path:
98
- chatgpt_output = img2txt(speech_to_text_output, image_path)
99
- writehistory(f"Image analysis: {chatgpt_output}")
 
 
 
 
 
 
 
100
  else:
101
  chatgpt_output = "No image provided."
102
- writehistory("No image provided")
103
-
104
  audio_output = text_to_speech(chatgpt_output)
 
105
  return speech_to_text_output, chatgpt_output, audio_output
106
-
107
  except Exception as e:
108
- writehistory(f"Error: {str(e)}")
109
  return str(e), str(e), None
110
 
111
  # Create Gradio interface
112
- iface = gr.Interface(
113
  fn=process_inputs,
114
  inputs=[
115
- gr.Audio(sources=["microphone"], type="filepath"),
116
- gr.Image(type="filepath")
117
  ],
118
  outputs=[
119
  gr.Textbox(label="Speech to Text"),
120
- gr.Textbox(label="Analysis Output"),
121
- gr.Audio()
122
  ],
123
- title="AI Image Analysis Assistant",
124
- description="Upload an image and ask questions using your voice. The AI will analyze the image and respond with voice and text.",
125
  )
126
 
127
- # Launch the app
128
  if __name__ == "__main__":
129
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
1
  import torch
2
+ from transformers import pipeline
3
  import whisper
4
  import gradio as gr
 
 
5
  from gtts import gTTS
6
  from PIL import Image
7
  import nltk
 
8
  import re
9
+ import tempfile
10
+ import os
11
+ import multiprocessing
12
 
13
+ # Enable multiprocessing for MacOS
14
+ multiprocessing.freeze_support()
 
15
 
16
+ # Download NLTK data
17
+ nltk.download('punkt', quiet=True)
 
 
 
18
 
19
+ # Configure device
 
 
 
 
 
 
20
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
21
+ print(f"Using device: {DEVICE}")
22
+
23
+ # Initialize a smaller vision model
24
+ model_id = "microsoft/git-base" # Using a more stable model
25
+ print("Loading image captioning model...")
26
+ pipe = None # We'll initialize this later to avoid multiprocessing issues
27
+
28
+ # Initialize Whisper model
29
+ print("Loading Whisper model...")
30
+ audio_model = None # We'll initialize this later
31
+
32
+ def initialize_models():
33
+ """Initialize models safely"""
34
+ global pipe, audio_model
35
+ if pipe is None:
36
+ pipe = pipeline("image-to-text", model=model_id)
37
+ if audio_model is None:
38
+ audio_model = whisper.load_model("tiny", device=DEVICE)
39
+ return pipe, audio_model
40
 
 
 
 
 
 
 
 
 
41
  def img2txt(input_text, input_image):
42
+ """Process image with the vision model"""
43
+ global pipe
44
+ if pipe is None:
45
+ pipe, _ = initialize_models()
46
 
47
+ try:
48
+ # Generate basic caption
49
+ outputs = pipe(input_image)
50
+ caption = outputs[0]['generated_text']
51
+
52
+ # If there's a specific question, append it to the response
53
+ if input_text and input_text.strip():
54
+ response = f"Based on the image which shows {caption}, "
55
+ response += f"addressing your question: {input_text}\n"
56
+ return response
57
+
58
+ return caption
59
+ except Exception as e:
60
+ print(f"Error in image processing: {str(e)}")
61
+ return "Sorry, I couldn't process the image properly."
 
 
 
 
 
 
62
 
63
  def transcribe(audio):
64
+ """Transcribe audio using Whisper"""
65
+ global audio_model
66
+ if audio_model is None:
67
+ _, audio_model = initialize_models()
68
+
69
+ if audio is None:
70
  return ''
71
 
72
+ try:
73
+ audio = whisper.load_audio(audio)
74
+ audio = whisper.pad_or_trim(audio)
75
+
76
+ mel = whisper.log_mel_spectrogram(audio).to(audio_model.device)
77
+ result = whisper.decode(audio_model, mel, whisper.DecodingOptions())
78
+
79
+ return result.text
80
+ except Exception as e:
81
+ print(f"Error in transcription: {str(e)}")
82
+ return "Sorry, I couldn't transcribe the audio properly."
83
 
84
+ def text_to_speech(text):
85
+ """Convert text to speech using gTTS"""
86
  try:
87
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
88
+ tts = gTTS(text=text, lang='en', slow=False)
89
+ tts.save(fp.name)
90
+ return fp.name
91
+ except Exception as e:
92
+ print(f"Error in text-to-speech: {str(e)}")
93
+ return None
94
 
95
+ def process_inputs(audio, image):
96
+ """Main processing function"""
97
+ try:
98
+ # Process speech to text
99
+ speech_to_text_output = transcribe(audio) if audio is not None else ""
100
+
101
+ # Process image and generate response
102
+ if image is not None:
103
+ query = speech_to_text_output if speech_to_text_output else "Describe this image in detail"
104
+ chatgpt_output = img2txt(query, image)
105
  else:
106
  chatgpt_output = "No image provided."
107
+
108
+ # Generate audio response
109
  audio_output = text_to_speech(chatgpt_output)
110
+
111
  return speech_to_text_output, chatgpt_output, audio_output
112
+
113
  except Exception as e:
114
+ print(f"Error in process_inputs: {str(e)}")
115
  return str(e), str(e), None
116
 
117
  # Create Gradio interface
118
+ demo = gr.Interface(
119
  fn=process_inputs,
120
  inputs=[
121
+ gr.Audio(sources=["microphone"], type="filepath", label="Voice Input"), # Fixed Audio component syntax
122
+ gr.Image(type="pil", label="Image Input") # Specified image type
123
  ],
124
  outputs=[
125
  gr.Textbox(label="Speech to Text"),
126
+ gr.Textbox(label="Image Analysis"),
127
+ gr.Audio(label="AI Response", type="filepath")
128
  ],
129
+ title="Image Analysis with Voice Interface",
130
+ description="Upload an image and ask questions using your voice. The AI will analyze the image and respond with both text and speech."
131
  )
132
 
 
133
  if __name__ == "__main__":
134
+ print("Starting Gradio interface...")
135
+ # Initialize models before launching the interface
136
+ initialize_models()
137
+ # Launch with minimal GPU memory usage
138
+ demo.launch(
139
+ share=True,
140
+ debug=True,
141
+ server_name="0.0.0.0",
142
+ server_port=7860,
143
+ )
img.png ADDED

Git LFS Details

  • SHA256: fdcc8514911bd85335cb8f18bb20e7b5c97e8b325bddd801fb34f06f14bbc8b2
  • Pointer size: 133 Bytes
  • Size of remote file: 22.3 MB