jon-fernandes commited on
Commit
3944d18
·
verified ·
1 Parent(s): 4648da9

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +54 -46
app.py CHANGED
@@ -5,7 +5,7 @@ from queue import Queue
5
  import threading
6
  import torch
7
  from PIL import Image, ImageOps
8
- from transformers import AutoProcessor, MiniCPMV4_6ForConditionalGeneration, TextIteratorStreamer
9
  import gradio as gr
10
 
11
  try:
@@ -88,6 +88,9 @@ def env_flag(name: str, default: bool = False) -> bool:
88
  return value.strip().lower() in {"1", "true", "yes", "on"}
89
 
90
 
 
 
 
91
  def _order_points(points):
92
  import numpy as np
93
 
@@ -294,54 +297,19 @@ print("Models loaded.")
294
  def stream_model(model, image: Image.Image):
295
  messages = [{
296
  "role": "user",
297
- "content": [
298
- {"type": "image", "image": image},
299
- {"type": "text", "text": NOTES_PROMPT},
300
- ],
301
  }]
302
 
303
  with torch.no_grad():
304
- inputs = processor.apply_chat_template(
305
- messages,
306
- add_generation_prompt=True,
307
- tokenize=True,
308
- return_dict=True,
309
- return_tensors="pt",
310
- enable_thinking=False,
311
- processor_kwargs={
312
- "downsample_mode": "4x",
313
- "max_slice_nums": 9,
314
- "use_image_id": True,
315
- },
316
- ).to(model.device)
317
-
318
- for k, v in inputs.items():
319
- if isinstance(v, torch.Tensor) and torch.is_floating_point(v):
320
- inputs[k] = v.to(dtype=torch.bfloat16)
321
-
322
- streamer = TextIteratorStreamer(
323
- processor.tokenizer,
324
- skip_prompt=True,
325
- skip_special_tokens=True,
326
- )
327
-
328
- thread = threading.Thread(
329
- target=model.generate,
330
- kwargs={
331
- **inputs,
332
- "max_new_tokens": 1024,
333
- "do_sample": False,
334
- "num_beams": 1,
335
- "streamer": streamer,
336
- "downsample_mode": "4x",
337
- },
338
- )
339
- thread.start()
340
-
341
- for chunk in streamer:
342
- yield chunk
343
 
344
- thread.join()
345
 
346
 
347
  def stream_model_text(model, image: Image.Image):
@@ -351,6 +319,47 @@ def stream_model_text(model, image: Image.Image):
351
  yield text
352
 
353
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  def _stream_openai_transcription(client, model_id, mime, image_data):
355
  response_stream = client.chat.completions.create(
356
  model=model_id,
@@ -547,7 +556,6 @@ with gr.Blocks(
547
  type="pil",
548
  label="Preprocessed Image Sent to All Models",
549
  interactive=False,
550
- show_download_button=True,
551
  )
552
  gr.Examples(
553
  examples=[
 
5
  import threading
6
  import torch
7
  from PIL import Image, ImageOps
8
+ from transformers import AutoProcessor, MiniCPMV4_6ForConditionalGeneration
9
  import gradio as gr
10
 
11
  try:
 
88
  return value.strip().lower() in {"1", "true", "yes", "on"}
89
 
90
 
91
+ ENABLE_MODEL_WARMUP = env_flag("NOTEWORTHY_WARMUP", True)
92
+
93
+
94
  def _order_points(points):
95
  import numpy as np
96
 
 
297
  def stream_model(model, image: Image.Image):
298
  messages = [{
299
  "role": "user",
300
+ "content": [image, NOTES_PROMPT],
 
 
 
301
  }]
302
 
303
  with torch.no_grad():
304
+ result = model.chat(
305
+ image=None,
306
+ msgs=messages,
307
+ tokenizer=processor.tokenizer,
308
+ sampling=False,
309
+ max_new_tokens=1024,
310
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
 
312
+ yield result or ""
313
 
314
 
315
  def stream_model_text(model, image: Image.Image):
 
319
  yield text
320
 
321
 
322
+ def warmup_models():
323
+ if not ENABLE_MODEL_WARMUP:
324
+ print("Model warmup disabled.")
325
+ return
326
+
327
+ warmup_path = "examples/000100005-1_1_1.png"
328
+ if not os.path.exists(warmup_path):
329
+ print("Skipping model warmup; example image is missing.")
330
+ return
331
+
332
+ print("Warming up local models...")
333
+ image, processed_image_path = preprocess_sheet_music_image(warmup_path)
334
+ try:
335
+ messages = [{
336
+ "role": "user",
337
+ "content": [image, NOTES_PROMPT],
338
+ }]
339
+ for name, model in (
340
+ ("fine-tuned", finetuned_model),
341
+ ("original", original_model),
342
+ ):
343
+ print(f" Warming {name} model...")
344
+ with torch.no_grad():
345
+ model.chat(
346
+ image=None,
347
+ msgs=messages,
348
+ tokenizer=processor.tokenizer,
349
+ sampling=False,
350
+ max_new_tokens=8,
351
+ )
352
+ print("Model warmup complete.")
353
+ finally:
354
+ try:
355
+ os.unlink(processed_image_path)
356
+ except OSError:
357
+ pass
358
+
359
+
360
+ warmup_models()
361
+
362
+
363
  def _stream_openai_transcription(client, model_id, mime, image_data):
364
  response_stream = client.chat.completions.create(
365
  model=model_id,
 
556
  type="pil",
557
  label="Preprocessed Image Sent to All Models",
558
  interactive=False,
 
559
  )
560
  gr.Examples(
561
  examples=[