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import AutoProcessor, AutoModelForCausalLM
|
| 3 |
+
import re
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import os
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
import spaces
|
| 9 |
+
import subprocess
|
| 10 |
+
subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
|
| 11 |
+
|
| 12 |
+
model = AutoModelForCausalLM.from_pretrained('thwri/CogFlorence-2.1-Large', trust_remote_code=True).to("cuda").eval()
|
| 13 |
+
processor = AutoProcessor.from_pretrained('thwri/CogFlorence-2.1-Large', trust_remote_code=True)
|
| 14 |
+
|
| 15 |
+
TITLE = "# [thwri/CogFlorence-2.1-Large]"
|
| 16 |
+
DESCRIPTION = "microsoft/Florence-2-large tuned on Ejafa/ye-pop captioned with CogVLM2"
|
| 17 |
+
|
| 18 |
+
def modify_caption(caption: str) -> str:
|
| 19 |
+
special_patterns = [
|
| 20 |
+
(r'the image is , ''),
|
| 21 |
+
(r'the image captures ', ''),
|
| 22 |
+
(r'the image showcases ', '')
|
| 23 |
+
(r'the image shows ', '')
|
| 24 |
+
(r'the image ', '')
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
for pattern, replacement in special_patterns:
|
| 28 |
+
caption = re.sub(pattern, replacement, caption, flags=re.IGNORECASE)
|
| 29 |
+
|
| 30 |
+
caption = caption.replace('\n', '').replace('\r', '')
|
| 31 |
+
caption = re.sub(r'(?<=[.,?!])(?=[^\s])', r' ', caption)
|
| 32 |
+
caption = ' '.join(caption.strip().splitlines())
|
| 33 |
+
|
| 34 |
+
return caption
|
| 35 |
+
|
| 36 |
+
@spaces.GPU
|
| 37 |
+
def process_image(image):
|
| 38 |
+
if isinstance(image, np.ndarray):
|
| 39 |
+
image = Image.fromarray(image)
|
| 40 |
+
elif isinstance(image, str):
|
| 41 |
+
image = Image.open(image)
|
| 42 |
+
if image.mode != "RGB":
|
| 43 |
+
image = image.convert("RGB")
|
| 44 |
+
|
| 45 |
+
prompt = "<MORE_DETAILED_CAPTION>"
|
| 46 |
+
|
| 47 |
+
inputs = processor(text=prompt, images=image, return_tensors="pt").to("cuda")
|
| 48 |
+
generated_ids = model.generate(
|
| 49 |
+
input_ids=inputs["input_ids"],
|
| 50 |
+
pixel_values=inputs["pixel_values"],
|
| 51 |
+
max_new_tokens=1024,
|
| 52 |
+
num_beams=3,
|
| 53 |
+
do_sample=True
|
| 54 |
+
)
|
| 55 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
|
| 56 |
+
parsed_answer = processor.post_process_generation(generated_text, task=prompt, image_size=(image.width, image.height))
|
| 57 |
+
return modify_caption(parsed_answer["<MORE_DETAILED_CAPTION>"])
|
| 58 |
+
|
| 59 |
+
def extract_frames(image_path, output_folder):
|
| 60 |
+
with Image.open(image_path) as img:
|
| 61 |
+
base_name = os.path.splitext(os.path.basename(image_path))[0]
|
| 62 |
+
frame_paths = []
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
for i in range(0, img.n_frames):
|
| 66 |
+
img.seek(i)
|
| 67 |
+
frame_path = os.path.join(output_folder, f"{base_name}_frame_{i:03d}.png")
|
| 68 |
+
img.save(frame_path)
|
| 69 |
+
frame_paths.append(frame_path)
|
| 70 |
+
except EOFError:
|
| 71 |
+
pass # We've reached the end of the sequence
|
| 72 |
+
|
| 73 |
+
return frame_paths
|
| 74 |
+
|
| 75 |
+
def process_folder(folder_path):
|
| 76 |
+
if not os.path.isdir(folder_path):
|
| 77 |
+
return "Invalid folder path."
|
| 78 |
+
|
| 79 |
+
processed_files = []
|
| 80 |
+
skipped_files = []
|
| 81 |
+
for filename in os.listdir(folder_path):
|
| 82 |
+
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.heic')):
|
| 83 |
+
image_path = os.path.join(folder_path, filename)
|
| 84 |
+
txt_filename = os.path.splitext(filename)[0] + '.txt'
|
| 85 |
+
txt_path = os.path.join(folder_path, txt_filename)
|
| 86 |
+
|
| 87 |
+
# Check if the corresponding text file already exists
|
| 88 |
+
if os.path.exists(txt_path):
|
| 89 |
+
skipped_files.append(f"Skipped {filename} (text file already exists)")
|
| 90 |
+
continue
|
| 91 |
+
|
| 92 |
+
# Check if the image has multiple frames
|
| 93 |
+
with Image.open(image_path) as img:
|
| 94 |
+
if getattr(img, "is_animated", False) and img.n_frames > 1:
|
| 95 |
+
# Extract frames
|
| 96 |
+
frames = extract_frames(image_path, folder_path)
|
| 97 |
+
for frame_path in frames:
|
| 98 |
+
frame_txt_filename = os.path.splitext(os.path.basename(frame_path))[0] + '.txt'
|
| 99 |
+
frame_txt_path = os.path.join(folder_path, frame_txt_filename)
|
| 100 |
+
|
| 101 |
+
# Check if the corresponding text file for the frame already exists
|
| 102 |
+
if os.path.exists(frame_txt_path):
|
| 103 |
+
skipped_files.append(f"Skipped {os.path.basename(frame_path)} (text file already exists)")
|
| 104 |
+
continue
|
| 105 |
+
|
| 106 |
+
caption = process_image(frame_path)
|
| 107 |
+
|
| 108 |
+
with open(frame_txt_path, 'w', encoding='utf-8') as f:
|
| 109 |
+
f.write(caption)
|
| 110 |
+
|
| 111 |
+
processed_files.append(f"Processed {os.path.basename(frame_path)} -> {frame_txt_filename}")
|
| 112 |
+
else:
|
| 113 |
+
# Process single image
|
| 114 |
+
caption = process_image(image_path)
|
| 115 |
+
|
| 116 |
+
with open(txt_path, 'w', encoding='utf-8') as f:
|
| 117 |
+
f.write(caption)
|
| 118 |
+
|
| 119 |
+
processed_files.append(f"Processed {filename} -> {txt_filename}")
|
| 120 |
+
|
| 121 |
+
result = "\n".join(processed_files + skipped_files)
|
| 122 |
+
return result if result else "No image files found or all files were skipped in the specified folder."
|
| 123 |
+
|
| 124 |
+
css = """
|
| 125 |
+
#output { height: 500px; overflow: auto; border: 1px solid #ccc; }
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
with gr.Blocks(css=css) as demo:
|
| 129 |
+
gr.Markdown(TITLE)
|
| 130 |
+
gr.Markdown(DESCRIPTION)
|
| 131 |
+
|
| 132 |
+
with gr.Tab(label="Single Image Processing"):
|
| 133 |
+
with gr.Row():
|
| 134 |
+
with gr.Column():
|
| 135 |
+
input_img = gr.Image(label="Input Picture")
|
| 136 |
+
submit_btn = gr.Button(value="Submit")
|
| 137 |
+
with gr.Column():
|
| 138 |
+
output_text = gr.Textbox(label="Output Text")
|
| 139 |
+
|
| 140 |
+
gr.Examples(
|
| 141 |
+
[["image1.jpg"], ["image2.jpg"], ["image3.png"], ["image4.jpg"], ["image5.jpg"], ["image6.PNG"]],
|
| 142 |
+
inputs=[input_img],
|
| 143 |
+
outputs=[output_text],
|
| 144 |
+
fn=process_image,
|
| 145 |
+
label='Try captioning on below examples'
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
submit_btn.click(process_image, [input_img], [output_text])
|
| 149 |
+
|
| 150 |
+
with gr.Tab(label="Batch Processing"):
|
| 151 |
+
with gr.Row():
|
| 152 |
+
folder_input = gr.Textbox(label="Input Folder Path")
|
| 153 |
+
batch_submit_btn = gr.Button(value="Process Folder")
|
| 154 |
+
batch_output = gr.Textbox(label="Batch Processing Results", lines=10)
|
| 155 |
+
|
| 156 |
+
batch_submit_btn.click(process_folder, [folder_input], [batch_output])
|
| 157 |
+
|
| 158 |
+
demo.launch(debug=True)
|