gokaygokay commited on
Commit
4e70ef0
1 Parent(s): 01758ed

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -0
app.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoProcessor, AutoModelForCausalLM
3
+ import spaces
4
+ import re
5
+ from PIL import Image
6
+
7
+ import subprocess
8
+ subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
9
+
10
+ model = AutoModelForCausalLM.from_pretrained('gokaygokay/Florence-2-SD3-Captioner', trust_remote_code=True).to("cuda").eval()
11
+
12
+ processor = AutoProcessor.from_pretrained('gokaygokay/Florence-2-SD3-Captioner', trust_remote_code=True)
13
+
14
+
15
+ TITLE = "# [Florence-2 SD3 Long Captioner](https://huggingface.co/gokaygokay/Florence-2-SD3-Captioner/)"
16
+
17
+ def modify_caption(caption: str) -> str:
18
+ """
19
+ Removes specific prefixes from captions.
20
+ Args:
21
+ caption (str): A string containing a caption.
22
+ Returns:
23
+ str: The caption with the prefix removed if it was present.
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: 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)]
38
+
39
+ # Apply the regex to the caption
40
+ return re.sub(pattern, replace_fn, caption, count=1, flags=re.IGNORECASE)
41
+
42
+ @spaces.GPU
43
+ def run_example(image):
44
+ image = Image.fromarray(image)
45
+ prompt = "<DESCRIPTION>" + "Describe this image in great detail."
46
+
47
+ # Ensure the image is in RGB mode
48
+ if image.mode != "RGB":
49
+ image = image.convert("RGB")
50
+
51
+ inputs = processor(text=prompt, images=image, return_tensors="pt").to(device)
52
+ generated_ids = model.generate(
53
+ input_ids=inputs["input_ids"],
54
+ pixel_values=inputs["pixel_values"],
55
+ max_new_tokens=1024,
56
+ num_beams=3
57
+ )
58
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
59
+ parsed_answer = processor.post_process_generation(generated_text, task=task_prompt, image_size=(image.width, image.height))
60
+ return modify_caption(parsed_answer["<DESCRIPTION>"])
61
+
62
+
63
+ css = """
64
+ #output {
65
+ height: 500px;
66
+ overflow: auto;
67
+ border: 1px solid #ccc;
68
+ }
69
+ """
70
+
71
+ with gr.Blocks(css=css) as demo:
72
+ gr.Markdown(TITLE)
73
+ with gr.Tab(label="Florence-2 SD3 Prompts"):
74
+ with gr.Row():
75
+ with gr.Column():
76
+ input_img = gr.Image(label="Input Picture")
77
+ submit_btn = gr.Button(value="Submit")
78
+ with gr.Column():
79
+ output_text = gr.Textbox(label="Output Text")
80
+
81
+ gr.Examples(
82
+ [["image1.jpg"], ["image2.jpg"], ["image3.png"], ["image4.jpg"], ["image5.jpg"], ["image6.PNG"]],
83
+ inputs = [input_img],
84
+ outputs = [output],
85
+ fn=run_example,
86
+ label='Try captioning on examples'
87
+ )
88
+
89
+ submit_btn.click(run_example, [input_img], [output_text])
90
+
91
+ demo.launch(debug=True)