bdsqlsz commited on
Commit
716f2ea
1 Parent(s): f24924b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -49
app.py CHANGED
@@ -1,58 +1,45 @@
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('microsoft/Florence-2-large', trust_remote_code=True).to("cuda").eval()
11
-
12
  processor = AutoProcessor.from_pretrained('microsoft/Florence-2-large', trust_remote_code=True)
13
 
14
-
15
  TITLE = "# [Florence-2 SD3 Long Captioner](https://huggingface.co/gokaygokay/Florence-2-SD3-Captioner/)"
16
  DESCRIPTION = "[Florence-2 Base](https://huggingface.co/microsoft/Florence-2-base-ft) fine-tuned on Long SD3 Prompt and Image pairs. Check above link for datasets that are used for fine-tuning."
17
 
18
  def modify_caption(caption: str) -> str:
19
- """
20
- Removes specific prefixes from captions if present, otherwise returns the original caption.
21
- Args:
22
- caption (str): A string containing a caption.
23
- Returns:
24
- str: The caption with the prefix removed if it was present, or the original caption.
25
- """
26
- # Define the prefixes to remove
27
- prefix_substrings = [
28
- ('captured from ', ''),
29
- ('captured at ', '')
30
  ]
31
 
32
- # Create a regex pattern to match any of the prefixes
33
- pattern = '|'.join([re.escape(opening) for opening, _ in prefix_substrings])
34
- replacers = {opening.lower(): replacer for opening, replacer in prefix_substrings}
35
-
36
- # Function to replace matched prefix with its corresponding replacement
37
- def replace_fn(match):
38
- return replacers[match.group(0).lower()]
39
 
40
- # Apply the regex to the caption
41
- modified_caption = re.sub(pattern, replace_fn, caption, count=1, flags=re.IGNORECASE)
 
42
 
43
- # If the caption was modified, return the modified version; otherwise, return the original
44
- return modified_caption if modified_caption != caption else caption
45
-
46
- @spaces.GPU
47
- def run_example(image):
48
- image = Image.fromarray(image)
49
- task_prompt = "<MORE_DETAILED_CAPTION>"
50
- prompt = task_prompt
51
 
52
- # Ensure the image is in RGB mode
 
 
 
 
 
53
  if image.mode != "RGB":
54
  image = image.convert("RGB")
55
-
 
 
56
  inputs = processor(text=prompt, images=image, return_tensors="pt").to("cuda")
57
  generated_ids = model.generate(
58
  input_ids=inputs["input_ids"],
@@ -61,37 +48,106 @@ def run_example(image):
61
  num_beams=3
62
  )
63
  generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
64
- parsed_answer = processor.post_process_generation(generated_text, task=task_prompt, image_size=(image.width, image.height))
65
  return modify_caption(parsed_answer["<MORE_DETAILED_CAPTION>"])
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  css = """
69
- #output {
70
- height: 500px;
71
- overflow: auto;
72
- border: 1px solid #ccc;
73
- }
74
  """
75
 
76
  with gr.Blocks(css=css) as demo:
77
  gr.Markdown(TITLE)
78
  gr.Markdown(DESCRIPTION)
79
- with gr.Tab(label="Florence-2 SD3 Prompts"):
 
80
  with gr.Row():
81
  with gr.Column():
82
  input_img = gr.Image(label="Input Picture")
83
  submit_btn = gr.Button(value="Submit")
84
  with gr.Column():
85
  output_text = gr.Textbox(label="Output Text")
86
-
87
  gr.Examples(
88
  [["image1.jpg"], ["image2.jpg"], ["image3.png"], ["image4.jpg"], ["image5.jpg"], ["image6.PNG"]],
89
- inputs = [input_img],
90
- outputs = [output_text],
91
- fn=run_example,
92
  label='Try captioning on below examples'
93
- )
 
 
94
 
95
- submit_btn.click(run_example, [input_img], [output_text])
 
 
 
 
 
 
96
 
97
  demo.launch(debug=True)
 
1
  import gradio as gr
2
  from transformers import AutoProcessor, AutoModelForCausalLM
 
3
  import re
4
  from PIL import Image
5
+ import os
6
+ import numpy as np
7
+ import space
8
 
9
  model = AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-large', trust_remote_code=True).to("cuda").eval()
 
10
  processor = AutoProcessor.from_pretrained('microsoft/Florence-2-large', trust_remote_code=True)
11
 
 
12
  TITLE = "# [Florence-2 SD3 Long Captioner](https://huggingface.co/gokaygokay/Florence-2-SD3-Captioner/)"
13
  DESCRIPTION = "[Florence-2 Base](https://huggingface.co/microsoft/Florence-2-base-ft) fine-tuned on Long SD3 Prompt and Image pairs. Check above link for datasets that are used for fine-tuning."
14
 
15
  def modify_caption(caption: str) -> str:
16
+ special_patterns = [
17
+ (r'The image shows ', ''), # 匹配 "The image shows " 并替换为空字符串
18
+ (r'The image is .*? of ', ''), # 匹配 "The image is .*? of" 并替换为空字符串
19
+ (r'of the .*? is', 'is') # 匹配 "of the .*? is" 并替换为 "is"
 
 
 
 
 
 
 
20
  ]
21
 
22
+ # 对每个特殊模式进行替换
23
+ for pattern, replacement in special_patterns:
24
+ caption = re.sub(pattern, replacement, caption, flags=re.IGNORECASE)
 
 
 
 
25
 
26
+ no_blank_lines = re.sub(r'\n\s*\n', '\n', caption)
27
+ # 合并内容
28
+ merged_content = ' '.join(no_blank_lines.strip().splitlines())
29
 
30
+ return merged_content if merged_content != caption else caption
 
 
 
 
 
 
 
31
 
32
+ @space.GPU
33
+ def process_image(image):
34
+ if isinstance(image, np.ndarray):
35
+ image = Image.fromarray(image)
36
+ elif isinstance(image, str):
37
+ image = Image.open(image)
38
  if image.mode != "RGB":
39
  image = image.convert("RGB")
40
+
41
+ prompt = "<MORE_DETAILED_CAPTION>"
42
+
43
  inputs = processor(text=prompt, images=image, return_tensors="pt").to("cuda")
44
  generated_ids = model.generate(
45
  input_ids=inputs["input_ids"],
 
48
  num_beams=3
49
  )
50
  generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
51
+ parsed_answer = processor.post_process_generation(generated_text, task=prompt, image_size=(image.width, image.height))
52
  return modify_caption(parsed_answer["<MORE_DETAILED_CAPTION>"])
53
 
54
+ def extract_frames(image_path, output_folder):
55
+ with Image.open(image_path) as img:
56
+ base_name = os.path.splitext(os.path.basename(image_path))[0]
57
+ frame_paths = []
58
+
59
+ try:
60
+ for i in range(0, img.n_frames):
61
+ img.seek(i)
62
+ frame_path = os.path.join(output_folder, f"{base_name}_frame_{i:03d}.png")
63
+ img.save(frame_path)
64
+ frame_paths.append(frame_path)
65
+ except EOFError:
66
+ pass # We've reached the end of the sequence
67
+
68
+ return frame_paths
69
+
70
+ def process_folder(folder_path):
71
+ if not os.path.isdir(folder_path):
72
+ return "Invalid folder path."
73
+
74
+ processed_files = []
75
+ skipped_files = []
76
+ for filename in os.listdir(folder_path):
77
+ if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.heic')):
78
+ image_path = os.path.join(folder_path, filename)
79
+ txt_filename = os.path.splitext(filename)[0] + '.txt'
80
+ txt_path = os.path.join(folder_path, txt_filename)
81
+
82
+ # Check if the corresponding text file already exists
83
+ if os.path.exists(txt_path):
84
+ skipped_files.append(f"Skipped {filename} (text file already exists)")
85
+ continue
86
+
87
+ # Check if the image has multiple frames
88
+ with Image.open(image_path) as img:
89
+ if getattr(img, "is_animated", False) and img.n_frames > 1:
90
+ # Extract frames
91
+ frames = extract_frames(image_path, folder_path)
92
+ for frame_path in frames:
93
+ frame_txt_filename = os.path.splitext(os.path.basename(frame_path))[0] + '.txt'
94
+ frame_txt_path = os.path.join(folder_path, frame_txt_filename)
95
+
96
+ # Check if the corresponding text file for the frame already exists
97
+ if os.path.exists(frame_txt_path):
98
+ skipped_files.append(f"Skipped {os.path.basename(frame_path)} (text file already exists)")
99
+ continue
100
+
101
+ caption = process_image(frame_path)
102
+
103
+ with open(frame_txt_path, 'w', encoding='utf-8') as f:
104
+ f.write(caption)
105
+
106
+ processed_files.append(f"Processed {os.path.basename(frame_path)} -> {frame_txt_filename}")
107
+ else:
108
+ # Process single image
109
+ caption = process_image(image_path)
110
+
111
+ with open(txt_path, 'w', encoding='utf-8') as f:
112
+ f.write(caption)
113
+
114
+ processed_files.append(f"Processed {filename} -> {txt_filename}")
115
+
116
+ result = "\n".join(processed_files + skipped_files)
117
+ return result if result else "No image files found or all files were skipped in the specified folder."
118
 
119
  css = """
120
+ #output { height: 500px; overflow: auto; border: 1px solid #ccc; }
 
 
 
 
121
  """
122
 
123
  with gr.Blocks(css=css) as demo:
124
  gr.Markdown(TITLE)
125
  gr.Markdown(DESCRIPTION)
126
+
127
+ with gr.Tab(label="Single Image Processing"):
128
  with gr.Row():
129
  with gr.Column():
130
  input_img = gr.Image(label="Input Picture")
131
  submit_btn = gr.Button(value="Submit")
132
  with gr.Column():
133
  output_text = gr.Textbox(label="Output Text")
134
+
135
  gr.Examples(
136
  [["image1.jpg"], ["image2.jpg"], ["image3.png"], ["image4.jpg"], ["image5.jpg"], ["image6.PNG"]],
137
+ inputs=[input_img],
138
+ outputs=[output_text],
139
+ fn=process_image,
140
  label='Try captioning on below examples'
141
+ )
142
+
143
+ submit_btn.click(process_image, [input_img], [output_text])
144
 
145
+ with gr.Tab(label="Batch Processing"):
146
+ with gr.Row():
147
+ folder_input = gr.Textbox(label="Input Folder Path")
148
+ batch_submit_btn = gr.Button(value="Process Folder")
149
+ batch_output = gr.Textbox(label="Batch Processing Results", lines=10)
150
+
151
+ batch_submit_btn.click(process_folder, [folder_input], [batch_output])
152
 
153
  demo.launch(debug=True)