alex buz commited on
Commit
f48278d
1 Parent(s): e1cddb8
Files changed (3) hide show
  1. app.py +139 -12
  2. pre-requirements.txt +1 -0
  3. requirements.txt +3 -2
app.py CHANGED
@@ -1,16 +1,143 @@
1
-
2
  import gradio as gr
3
- from transformers import pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- pipeline = pipeline(task="image-classification", model="julien-c/hotdog-not-hotdog")
 
 
 
 
 
 
 
 
 
 
6
 
7
- def predict(image):
8
- predictions = pipeline(image)
9
- return {p["label"]: p["score"] for p in predictions}
10
 
11
- gr.Interface(
12
- predict,
13
- inputs=gr.Image(label="Upload hot dog candidate", type="filepath"),
14
- outputs=gr.Label(num_top_classes=2),
15
- title="Hot Dog? Or Not?",
16
- ).launch()
 
 
1
  import gradio as gr
2
+ from transformers import AutoProcessor, AutoModelForCausalLM
3
+ import spaces
4
+
5
+ import requests
6
+ import copy
7
+
8
+ from PIL import Image, ImageDraw, ImageFont
9
+ import io
10
+ import matplotlib.pyplot as plt
11
+ import matplotlib.patches as patches
12
+
13
+ import random
14
+ import numpy as np
15
+
16
+ import subprocess
17
+ subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
18
+
19
+ models = {
20
+ 'microsoft/Florence-2-large-ft': AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-large-ft', trust_remote_code=True).to("cuda").eval(),
21
+ 'microsoft/Florence-2-large': AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-large', trust_remote_code=True).to("cuda").eval(),
22
+ 'microsoft/Florence-2-base-ft': AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-base-ft', trust_remote_code=True).to("cuda").eval(),
23
+ 'microsoft/Florence-2-base': AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True).to("cuda").eval(),
24
+ }
25
+
26
+ processors = {
27
+ 'microsoft/Florence-2-large-ft': AutoProcessor.from_pretrained('microsoft/Florence-2-large-ft', trust_remote_code=True),
28
+ 'microsoft/Florence-2-large': AutoProcessor.from_pretrained('microsoft/Florence-2-large', trust_remote_code=True),
29
+ 'microsoft/Florence-2-base-ft': AutoProcessor.from_pretrained('microsoft/Florence-2-base-ft', trust_remote_code=True),
30
+ 'microsoft/Florence-2-base': AutoProcessor.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True),
31
+ }
32
+
33
+
34
+ DESCRIPTION = "# [Florence-2 OCR Demo](https://huggingface.co/microsoft/Florence-2-large)"
35
+
36
+ colormap = ['blue','orange','green','purple','brown','pink','gray','olive','cyan','red',
37
+ 'lime','indigo','violet','aqua','magenta','coral','gold','tan','skyblue']
38
+
39
+ def fig_to_pil(fig):
40
+ buf = io.BytesIO()
41
+ fig.savefig(buf, format='png')
42
+ buf.seek(0)
43
+ return Image.open(buf)
44
+
45
+ @spaces.GPU
46
+ def run_example(task_prompt, image, text_input=None, model_id='microsoft/Florence-2-large'):
47
+ model = models[model_id]
48
+ processor = processors[model_id]
49
+ if text_input is None:
50
+ prompt = task_prompt
51
+ else:
52
+ prompt = task_prompt + text_input
53
+ inputs = processor(text=prompt, images=image, return_tensors="pt").to("cuda")
54
+ generated_ids = model.generate(
55
+ input_ids=inputs["input_ids"],
56
+ pixel_values=inputs["pixel_values"],
57
+ max_new_tokens=1024,
58
+ early_stopping=False,
59
+ do_sample=False,
60
+ num_beams=3,
61
+ )
62
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
63
+ parsed_answer = processor.post_process_generation(
64
+ generated_text,
65
+ task=task_prompt,
66
+ image_size=(image.width, image.height)
67
+ )
68
+ return parsed_answer
69
+
70
+
71
+
72
+
73
+ def process_image(image, task_prompt, text_input=None, model_id='microsoft/Florence-2-large'):
74
+ image = Image.fromarray(image) # Convert NumPy array to PIL Image
75
+
76
+ if task_prompt == 'OCR':
77
+ task_prompt = '<OCR>'
78
+ results = run_example(task_prompt, image, model_id=model_id)
79
+ return results, None
80
+ else:
81
+ return "", None # Return empty string and None for unknown task prompts
82
+
83
+ css = """
84
+ #output {
85
+ height: 500px;
86
+ overflow: auto;
87
+ border: 1px solid #ccc;
88
+ }
89
+ """
90
+
91
+
92
+ single_task_list =[
93
+ 'Caption', 'Detailed Caption', 'More Detailed Caption', 'Object Detection',
94
+ 'Dense Region Caption', 'Region Proposal', 'Caption to Phrase Grounding',
95
+ 'Referring Expression Segmentation', 'Region to Segmentation',
96
+ 'Open Vocabulary Detection', 'Region to Category', 'Region to Description',
97
+ 'OCR', 'OCR with Region'
98
+ ]
99
+
100
+ cascased_task_list =[
101
+ 'Caption + Grounding', 'Detailed Caption + Grounding', 'More Detailed Caption + Grounding'
102
+ ]
103
+
104
+
105
+ def update_task_dropdown(choice):
106
+ if choice == 'Cascased task':
107
+ return gr.Dropdown(choices=cascased_task_list, value='Caption + Grounding')
108
+ else:
109
+ return gr.Dropdown(choices=single_task_list, value='Caption')
110
+
111
+
112
+
113
+ with gr.Blocks(css=css) as demo:
114
+ gr.Markdown(DESCRIPTION)
115
+ with gr.Tab(label="Florence-2 Image Captioning"):
116
+ with gr.Row():
117
+ with gr.Column():
118
+ input_img = gr.Image(label="Input Picture")
119
+ model_selector = gr.Dropdown(choices=list(models.keys()), label="Model", value='microsoft/Florence-2-large')
120
+ task_type = gr.Radio(choices=['Single task', 'Cascased task'], label='Task type selector', value='Single task')
121
+ task_prompt = gr.Dropdown(choices=single_task_list, label="Task Prompt", value="Caption")
122
+ task_type.change(fn=update_task_dropdown, inputs=task_type, outputs=task_prompt)
123
+ text_input = gr.Textbox(label="Text Input (optional)")
124
+ submit_btn = gr.Button(value="Submit")
125
+ with gr.Column():
126
+ output_text = gr.Textbox(label="Output Text")
127
+
128
 
129
+ gr.Examples(
130
+ examples=[
131
+ ["image1.jpg", 'Object Detection'],
132
+ ["image2.jpg", 'OCR with Region']
133
+ ],
134
+ inputs=[input_img, task_prompt],
135
+ outputs=[output_text],
136
+ fn=process_image,
137
+ cache_examples=True,
138
+ label='Try examples'
139
+ )
140
 
141
+ submit_btn.click(process_image, [input_img, task_prompt, text_input, model_selector], [output_text])
 
 
142
 
143
+ demo.launch(debug=True)
 
 
 
 
 
pre-requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pip>=23.0.0
requirements.txt CHANGED
@@ -1,2 +1,3 @@
1
- transformers
2
- torch
 
 
1
+ spaces
2
+ transformers
3
+ timm