vumichien commited on
Commit
7517cd1
1 Parent(s): dfb56df

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -0
app.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoProcessor, AutoModelForCausalLM
3
+ import re
4
+ from PIL import Image
5
+
6
+ import subprocess
7
+ subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
8
+
9
+ model = AutoModelForCausalLM.from_pretrained('vumichien/Florence-2-FT-Caption', trust_remote_code=True).to("cpu").eval()
10
+
11
+ processor = AutoProcessor.from_pretrained('vumichien/Florence-2-FT-Caption', trust_remote_code=True)
12
+
13
+
14
+ TITLE = "# [Florence-2 Captioner](https://huggingface.co/vumichien/Florence-2-FT-Caption)"
15
+
16
+
17
+ def modify_caption(caption: str) -> str:
18
+ """
19
+ Removes specific prefixes from captions if present, otherwise returns the original caption.
20
+ Args:
21
+ caption (str): A string containing a caption.
22
+ Returns:
23
+ str: The caption with the prefix removed if it was present, or the original caption.
24
+ """
25
+ # Define the prefixes to remove
26
+ prefix_substrings = [
27
+ ('captured from ', ''),
28
+ ('captured at ', '')
29
+ ]
30
+
31
+ # Create a regex pattern to match any of the prefixes
32
+ pattern = '|'.join([re.escape(opening) for opening, _ in prefix_substrings])
33
+ replacers = {opening.lower(): replacer for opening, replacer in prefix_substrings}
34
+
35
+ # Function to replace matched prefix with its corresponding replacement
36
+ def replace_fn(match):
37
+ return replacers[match.group(0).lower()]
38
+
39
+ # Apply the regex to the caption
40
+ modified_caption = re.sub(pattern, replace_fn, caption, count=1, flags=re.IGNORECASE)
41
+
42
+ # If the caption was modified, return the modified version; otherwise, return the original
43
+ return modified_caption if modified_caption != caption else caption
44
+
45
+ #@spaces.GPU
46
+ def run_example(image):
47
+ image = Image.fromarray(image)
48
+ task_prompt = "<CAPTION>"
49
+ prompt = task_prompt
50
+
51
+ # Ensure the image is in RGB mode
52
+ if image.mode != "RGB":
53
+ image = image.convert("RGB")
54
+
55
+ inputs = processor(text=prompt, images=image, return_tensors="pt").to("cpu")
56
+ generated_ids = model.generate(
57
+ input_ids=inputs["input_ids"],
58
+ pixel_values=inputs["pixel_values"],
59
+ max_new_tokens=1024,
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(generated_text, task=task_prompt, image_size=(image.width, image.height))
64
+ return modify_caption(parsed_answer["<CAPTION>"])
65
+
66
+
67
+ css = """
68
+ #output {
69
+ height: 500px;
70
+ overflow: auto;
71
+ border: 1px solid #ccc;
72
+ }
73
+ """
74
+ examples = ["240617143250078.JPG", "240617144124216.JPG", "240617144154631.JPG", "240617160707848.JPG"]
75
+
76
+ with gr.Blocks(css=css) as demo:
77
+ gr.Markdown(TITLE)
78
+ with gr.Tab(label="Florence-2 SD3 Prompts"):
79
+ with gr.Row():
80
+ with gr.Column():
81
+ input_img = gr.Image(label="Input Picture",height=400)
82
+ submit_btn = gr.Button(value="Submit")
83
+ with gr.Column():
84
+ output_text = gr.Textbox(label="Output Text")
85
+
86
+ submit_btn.click(run_example, [input_img], [output_text])
87
+ examples = gr.Examples(
88
+ examples,
89
+ fn=run_example,
90
+ inputs=[input_img],
91
+ outputs=output,
92
+ cache_examples=True,
93
+ )
94
+
95
+ demo.launch(debug=True)