Frederic-CellNum commited on
Commit
725766b
·
verified ·
1 Parent(s): fc672ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -57
app.py CHANGED
@@ -153,6 +153,10 @@
153
 
154
  # demo.queue(api_open=True)
155
  # demo.launch(debug=True)
 
 
 
 
156
  import gradio as gr
157
  import spaces
158
  from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
@@ -161,36 +165,34 @@ from PIL import Image
161
  from datetime import datetime
162
  import os
163
 
164
- # subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
165
-
166
  DESCRIPTION = "[Sparrow Qwen2-VL-7B Backend](https://github.com/katanaml/sparrow)"
167
 
 
 
 
 
 
 
 
 
 
168
 
169
  def array_to_image_path(image_filepath, max_width=1250, max_height=1750):
170
  if image_filepath is None:
171
  raise ValueError("No image provided. Please upload an image before submitting.")
172
 
173
- # Open the uploaded image using its filepath
174
  img = Image.open(image_filepath)
 
175
 
176
- # Extract the file extension from the uploaded file
177
- input_image_extension = image_filepath.split('.')[-1].lower() # Extract extension from filepath
178
-
179
- # Set file extension based on the original file, otherwise default to PNG
180
  if input_image_extension in ['jpg', 'jpeg', 'png']:
181
  file_extension = input_image_extension
182
  else:
183
- file_extension = 'png' # Default to PNG if extension is unavailable or invalid
184
 
185
- # Get the current dimensions of the image
186
  width, height = img.size
187
-
188
- # Initialize new dimensions to current size
189
  new_width, new_height = width, height
190
 
191
- # Check if the image exceeds the maximum dimensions
192
  if width > max_width or height > max_height:
193
- # Calculate the new size, maintaining the aspect ratio
194
  aspect_ratio = width / height
195
 
196
  if width > max_width:
@@ -201,60 +203,38 @@ def array_to_image_path(image_filepath, max_width=1250, max_height=1750):
201
  new_height = max_height
202
  new_width = int(new_height * aspect_ratio)
203
 
204
- # Generate a unique filename using timestamp
205
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
206
  filename = f"image_{timestamp}.{file_extension}"
207
-
208
- # Save the image
209
  img.save(filename)
210
-
211
- # Get the full path of the saved image
212
  full_path = os.path.abspath(filename)
213
 
214
  return full_path, new_width, new_height
215
 
216
 
217
- # CORRECTION: Ne pas initialiser le modèle dans le scope global
218
- # À la place, on va le charger dans la fonction décorée avec @spaces.GPU
219
-
220
- # Cache global pour éviter de recharger le modèle à chaque appel
221
- _model_cache = {}
222
-
223
- def get_model_and_processor():
224
  """
225
- Charge le modèle et le processeur une seule fois et les met en cache
226
- Cette fonction doit être appelée UNIQUEMENT dans une fonction @spaces.GPU
227
  """
228
- if 'model' not in _model_cache:
229
- print("Chargement du modèle Qwen2-VL-7B-Instruct...")
230
- _model_cache['model'] = Qwen2VLForConditionalGeneration.from_pretrained(
 
 
 
231
  "Qwen/Qwen2-VL-7B-Instruct",
232
  torch_dtype="auto",
233
  device_map="auto"
234
  )
235
- _model_cache['processor'] = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
236
- print("Modèle chargé avec succès!")
237
-
238
- return _model_cache['model'], _model_cache['processor']
239
-
240
-
241
- @spaces.GPU
242
- def run_inference(input_imgs, text_input):
243
- """
244
- CORRECTION: Le modèle est maintenant chargé ICI, à l'intérieur de la fonction @spaces.GPU
245
- Cela évite l'erreur "CUDA must not be initialized in the main process"
246
- """
247
- # Charger le modèle et le processeur dans la fonction GPU
248
- model, processor = get_model_and_processor()
249
 
250
  results = []
251
 
252
  for image in input_imgs:
253
- # Convert each image to the required format
254
  image_path, width, height = array_to_image_path(image)
255
 
256
  try:
257
- # Prepare messages for each image
258
  messages = [
259
  {
260
  "role": "user",
@@ -273,13 +253,12 @@ def run_inference(input_imgs, text_input):
273
  }
274
  ]
275
 
276
- # Prepare inputs for the model
277
- text = processor.apply_chat_template(
278
  messages, tokenize=False, add_generation_prompt=True
279
  )
280
 
281
  image_inputs, video_inputs = process_vision_info(messages)
282
- inputs = processor(
283
  text=[text],
284
  images=image_inputs,
285
  videos=video_inputs,
@@ -288,23 +267,24 @@ def run_inference(input_imgs, text_input):
288
  )
289
  inputs = inputs.to("cuda")
290
 
291
- # Generate inference output
292
- generated_ids = model.generate(**inputs, max_new_tokens=4096)
293
  generated_ids_trimmed = [
294
  out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
295
  ]
296
- raw_output = processor.batch_decode(
297
  generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=True
298
  )
299
 
300
  results.append(raw_output[0])
301
- print("Processed: " + image)
 
 
 
302
  finally:
303
- # Clean up the temporary image file
304
  if os.path.exists(image_path):
305
  os.remove(image_path)
306
 
307
- return results
308
 
309
 
310
  css = """
@@ -321,10 +301,10 @@ with gr.Blocks(css=css) as demo:
321
  with gr.Row():
322
  with gr.Column():
323
  input_imgs = gr.Files(file_types=["image"], label="Upload Document Images")
324
- text_input = gr.Textbox(label="Query")
325
  submit_btn = gr.Button(value="Submit", variant="primary")
326
  with gr.Column():
327
- output_text = gr.Textbox(label="Response")
328
 
329
  submit_btn.click(run_inference, [input_imgs, text_input], [output_text])
330
 
 
153
 
154
  # demo.queue(api_open=True)
155
  # demo.launch(debug=True)
156
+
157
+
158
+
159
+
160
  import gradio as gr
161
  import spaces
162
  from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
 
165
  from datetime import datetime
166
  import os
167
 
 
 
168
  DESCRIPTION = "[Sparrow Qwen2-VL-7B Backend](https://github.com/katanaml/sparrow)"
169
 
170
+ # ============================================================================
171
+ # IMPORTANT: NE PAS charger le modèle ici (scope global)
172
+ # Le modèle doit être chargé UNIQUEMENT dans la fonction @spaces.GPU
173
+ # ============================================================================
174
+
175
+ # Variables globales pour le cache (sans charger le modèle)
176
+ _model = None
177
+ _processor = None
178
+
179
 
180
  def array_to_image_path(image_filepath, max_width=1250, max_height=1750):
181
  if image_filepath is None:
182
  raise ValueError("No image provided. Please upload an image before submitting.")
183
 
 
184
  img = Image.open(image_filepath)
185
+ input_image_extension = image_filepath.split('.')[-1].lower()
186
 
 
 
 
 
187
  if input_image_extension in ['jpg', 'jpeg', 'png']:
188
  file_extension = input_image_extension
189
  else:
190
+ file_extension = 'png'
191
 
 
192
  width, height = img.size
 
 
193
  new_width, new_height = width, height
194
 
 
195
  if width > max_width or height > max_height:
 
196
  aspect_ratio = width / height
197
 
198
  if width > max_width:
 
203
  new_height = max_height
204
  new_width = int(new_height * aspect_ratio)
205
 
 
206
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
207
  filename = f"image_{timestamp}.{file_extension}"
 
 
208
  img.save(filename)
 
 
209
  full_path = os.path.abspath(filename)
210
 
211
  return full_path, new_width, new_height
212
 
213
 
214
+ @spaces.GPU
215
+ def run_inference(input_imgs, text_input):
 
 
 
 
 
216
  """
217
+ CORRECTION CRITIQUE: Le modèle est chargé ICI, pas dans le scope global
 
218
  """
219
+ global _model, _processor
220
+
221
+ # Charger le modèle uniquement la première fois (lazy loading)
222
+ if _model is None or _processor is None:
223
+ print("🔄 Chargement du modèle Qwen2-VL-7B-Instruct...")
224
+ _model = Qwen2VLForConditionalGeneration.from_pretrained(
225
  "Qwen/Qwen2-VL-7B-Instruct",
226
  torch_dtype="auto",
227
  device_map="auto"
228
  )
229
+ _processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
230
+ print("Modèle chargé avec succès!")
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
  results = []
233
 
234
  for image in input_imgs:
 
235
  image_path, width, height = array_to_image_path(image)
236
 
237
  try:
 
238
  messages = [
239
  {
240
  "role": "user",
 
253
  }
254
  ]
255
 
256
+ text = _processor.apply_chat_template(
 
257
  messages, tokenize=False, add_generation_prompt=True
258
  )
259
 
260
  image_inputs, video_inputs = process_vision_info(messages)
261
+ inputs = _processor(
262
  text=[text],
263
  images=image_inputs,
264
  videos=video_inputs,
 
267
  )
268
  inputs = inputs.to("cuda")
269
 
270
+ generated_ids = _model.generate(**inputs, max_new_tokens=4096)
 
271
  generated_ids_trimmed = [
272
  out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
273
  ]
274
+ raw_output = _processor.batch_decode(
275
  generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=True
276
  )
277
 
278
  results.append(raw_output[0])
279
+ print(f"Processed: {image}")
280
+ except Exception as e:
281
+ print(f"❌ Error processing {image}: {str(e)}")
282
+ results.append(f"Error: {str(e)}")
283
  finally:
 
284
  if os.path.exists(image_path):
285
  os.remove(image_path)
286
 
287
+ return "\n\n---\n\n".join(results)
288
 
289
 
290
  css = """
 
301
  with gr.Row():
302
  with gr.Column():
303
  input_imgs = gr.Files(file_types=["image"], label="Upload Document Images")
304
+ text_input = gr.Textbox(label="Query", placeholder="Enter your query here...")
305
  submit_btn = gr.Button(value="Submit", variant="primary")
306
  with gr.Column():
307
+ output_text = gr.Textbox(label="Response", elem_id="output")
308
 
309
  submit_btn.click(run_inference, [input_imgs, text_input], [output_text])
310