Spaces:
Sleeping
Sleeping
File size: 16,867 Bytes
ef07723 7cbc044 ef07723 7cbc044 ef07723 7cbc044 ef07723 7cbc044 ef07723 7cbc044 ef07723 520d0cf ef07723 520d0cf ef07723 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 |
# -*- coding: utf-8 -*-
# --- ํ์ํ ๋ชจ๋ ์ํฌํธ ---
import gradio as gr
from transformers import DonutProcessor, VisionEncoderDecoderModel
from PIL import Image
import torch
import re
import json
import os
import warnings
# --- ๊ฒฝ๊ณ ๋ฉ์์ง ๋ฌด์ ---
# UserWarning: TypedStorage is deprecated ๋ PyTorch ๊ด๋ จ ๊ฒฝ๊ณ ๋ก ๋ฌด์ํด๋ ๊ด์ฐฎ์ต๋๋ค.
warnings.filterwarnings("ignore", category=UserWarning, message="TypedStorage is deprecated")
# Future or other warnings if needed
warnings.filterwarnings("ignore", category=FutureWarning)
# --- ๋ชจ๋ธ ๋ฐ ํ๋ก์ธ์ ๊ฒฝ๋ก ์ ์ ---
# Hugging Face Spaces ์ ์ฅ์ ๋ด๋ถ์ ๋ชจ๋ธ ํ์ผ์ ๋ณต์ฌํ๋ค๊ณ ๊ฐ์ ํฉ๋๋ค.
# ์ ์ฅ์ ๋ฃจํธ์ donut_sroie_finetuned ํด๋๊ฐ ์๊ณ ๊ทธ ์์ final_model ์ด ์๋ ๊ตฌ์กฐ
model_path_finetuned = "greene6517/finetuned_donut_sroie"
model_name_base = "naver-clova-ix/donut-base" # Base ๋ชจ๋ธ์ Hub์์ ์ง์ ๋ก๋
# --- Fine-tuned Processor ๋ฐ ๋ชจ๋ธ ๋ก๋ฉ ---
print(f"Loading Fine-tuned processor from Hub: {model_path_finetuned}") # ๋ก๊ทธ ๋ฉ์์ง๋ ํ์ธ
try:
# local_files_only=True ๊ฐ ์์ด์ผ ํจ! model_path_finetuned ๋ณ์ ์ฌ์ฉ ํ์ธ!
processor = DonutProcessor.from_pretrained(model_path_finetuned)
print("Successfully loaded fine-tuned processor from Hub.")
except Exception as e:
print(f"FATAL: Could not load fine-tuned processor from Hub: {e}")
exit()
print(f"Loading Fine-tuned model from Hub: {model_path_finetuned}") # ๋ก๊ทธ ๋ฉ์์ง๋ ํ์ธ
try:
# local_files_only=True ๊ฐ ์์ด์ผ ํจ! model_path_finetuned ๋ณ์ ์ฌ์ฉ ํ์ธ!
model_finetuned = VisionEncoderDecoderModel.from_pretrained(model_path_finetuned)
print("Successfully loaded fine-tuned model from Hub.")
except Exception as e:
print(f"FATAL: Could not load fine-tuned model from Hub: {e}")
exit()
print(f"Loading Fine-tuned model from: {model_path_finetuned}")
try:
# local_files_only=True ๋ฅผ ์ฌ์ฉํ์ฌ Spaces ์ ์ฅ์ ๋ด ํ์ผ๋ง ์ฌ์ฉํ๋๋ก ๊ฐ์
model_finetuned = VisionEncoderDecoderModel.from_pretrained(model_path_finetuned, local_files_only=True)
print("Successfully loaded fine-tuned model locally from Space repo.")
except Exception as e:
print(f"Error loading fine-tuned model locally: {e}. Check if model files exist at the path.")
# ํ์์ Hub์์ ๋ก๋ ์๋ํ๋ ๋ก์ง ์ถ๊ฐ ๊ฐ๋ฅ (๋จ, ๋ชจ๋ธ์ด Hub์ ์
๋ก๋ ๋์ด ์์ด์ผ ํจ)
# try:
# model_finetuned = VisionEncoderDecoderModel.from_pretrained("your-hf-username/your-model-repo-name") # Hub ๊ฒฝ๋ก ์์
# print("Loaded fine-tuned model from Hub as fallback.")
# except Exception as e2:
# print(f"FATAL: Could not load fine-tuned model locally or from Hub: {e2}")
# exit()
# ์ฌ๊ธฐ์๋ ๋ก์ปฌ ๋ก๋ฉ ์คํจ ์ ์ผ๋จ ์ข
๋ฃํ๋๋ก ํจ (์์ ํ์์ ์ฃผ์ ํด์ )
print(f"FATAL: Could not load fine-tuned model locally: {e}")
exit()
# --- Base Processor ๋ฐ ๋ชจ๋ธ ๋ก๋ฉ (Hub์์ ์ง์ ) ---
print(f"Loading Base processor from: {model_name_base}")
try:
processor_base = DonutProcessor.from_pretrained(model_name_base)
print("Successfully loaded base processor.")
except Exception as e:
print(f"FATAL: Could not load base processor: {e}")
exit()
print(f"Loading Base model from: {model_name_base}")
try:
model_base = VisionEncoderDecoderModel.from_pretrained(model_name_base)
print("Successfully loaded base model.")
except Exception as e:
print(f"FATAL: Could not load base model: {e}")
exit()
# --- ์ฅ์น ์ค์ ๋ฐ ๋ชจ๋ธ ์ด๋ ---
# Spaces ํ๊ฒฝ์์๋ CPU ๋๋ ํ ๋น๋ GPU๋ฅผ ์ฌ์ฉํฉ๋๋ค.
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"\nUsing device: {device}")
# ๋ชจ๋ธ์ ํด๋น ์ฅ์น๋ก ์ด๋
try:
model_finetuned.to(device)
model_base.to(device)
print("Models moved to device.")
# ํ๊ฐ ๋ชจ๋ ์ค์ (ํ์)
model_finetuned.eval()
model_base.eval()
print("Models set to evaluation mode.")
except Exception as e:
print(f"Error moving models to device or setting eval mode: {e}")
exit()
# --- Helper function to clean generated sequence (์ฃผ๋ก Fine-tuned์ฉ) ---
def clean_sequence(sequence, processor_to_use, prompt_token_str=None):
"""Removes prompt, EOS, PAD tokens from a generated sequence."""
cleaned = sequence
try:
# Standard tokens first
eos_token = processor_to_use.tokenizer.eos_token if processor_to_use.tokenizer.eos_token else "</s>" # Default EOS
pad_token = processor_to_use.tokenizer.pad_token if processor_to_use.tokenizer.pad_token else "<pad>" # Default PAD
cleaned = cleaned.replace(eos_token, "").replace(pad_token, "").strip()
# Add BOS token removal if it exists and appears
if hasattr(processor_to_use.tokenizer, 'bos_token') and processor_to_use.tokenizer.bos_token:
cleaned = cleaned.replace(processor_to_use.tokenizer.bos_token, "").strip()
# Specific prompt removal (case-insensitive start check can be robust)
if prompt_token_str:
# Simple startswith check might be enough if prompt is always at the beginning
if cleaned.startswith(prompt_token_str):
cleaned = cleaned[len(prompt_token_str):].strip()
# Regex version (more robust but slightly slower)
# cleaned = re.sub(f"^{re.escape(prompt_token_str)}", "", cleaned, flags=re.IGNORECASE).strip()
except Exception as e:
print(f"Warning: Error during sequence cleaning: {e}")
return sequence # Return original if cleaning fails
return cleaned
# --- Helper function to parse SROIE format ---
def token2json_simple(text):
"""Parses <s_key>value</s_key> format into a dictionary."""
output = {}
# Regex to find <s_...>...</s_...> patterns, handling potential spaces and newlines in value
# It captures the key name (e.g., "company") and the value between the tags.
parts = re.findall(r"<s_(.*?)>([\s\S]*?)</s_\1>", text)
for key, value in parts:
# Strip leading/trailing whitespace from key and value
output[key.strip()] = value.strip()
# Add info if parsing failed but text was present
if not output and text and not text.isspace():
output["parsing_info"] = "Could not parse SROIE key-value pairs from the cleaned sequence."
output["cleaned_sequence_preview"] = text[:200] + "..." # Show preview
elif not text or text.isspace():
output["parsing_info"] = "Empty sequence after cleaning, nothing to parse."
return output
# --- ํตํฉ ์ด๋ฏธ์ง ์ฒ๋ฆฌ ๋ฐ ์ถ๋ก ํจ์ ---
# ๋ฐ์ฝ๋ ์ดํฐ ์ถ๊ฐ: ๊ทธ๋๋์ธํธ ๊ณ์ฐ ๋นํ์ฑํ (์ถ๋ก ์ ๋ฉ๋ชจ๋ฆฌ ์ ์ฝ ๋ฐ ์๋ ํฅ์)
@torch.no_grad()
def process_image_comparison(image_input):
if image_input is None:
no_image_msg = {"error": "์ด๋ฏธ์ง๋ฅผ ์
๋ก๋ํด์ฃผ์ธ์."}
# Ensure JSON output for Gradio component
return json.dumps(no_image_msg, indent=2, ensure_ascii=False), json.dumps(no_image_msg, indent=2, ensure_ascii=False)
try:
# Gradio's numpy input needs conversion
image = Image.fromarray(image_input).convert("RGB")
except Exception as e:
error_msg = {"error": f"์ด๋ฏธ์ง ๋ณํ ์ค๋ฅ: {e}"}
error_json_str = json.dumps(error_msg, indent=2, ensure_ascii=False)
return error_json_str, error_json_str
results_ft_json_str = "{}"
results_base_json_str = "{}"
sequence_ft_raw = "N/A"
sequence_base_raw = "N/A"
# === Fine-tuned ๋ชจ๋ธ ์ถ๋ก ===
try:
pixel_values_ft = processor(image, return_tensors="pt").pixel_values.to(device)
task_prompt_ft = "<s_sroie>" # Fine-tuned ๋ชจ๋ธ์ ์์ ํ๋กฌํํธ
decoder_input_ids_ft = processor.tokenizer(
task_prompt_ft, add_special_tokens=False, return_tensors="pt"
).input_ids.to(device)
# ์์ฑ ์ ํ์ํ ํ๋ผ๋ฏธํฐ ์ค์
generation_config_ft = {
"max_length": model_finetuned.config.decoder.max_position_embeddings,
"pad_token_id": processor.tokenizer.pad_token_id,
"eos_token_id": processor.tokenizer.eos_token_id,
"use_cache": True,
"bad_words_ids": [[processor.tokenizer.unk_token_id]] if processor.tokenizer.unk_token_id else None,
"return_dict_in_generate": True,
"decoder_input_ids": decoder_input_ids_ft # ์์ ํ๋กฌํํธ ์ ๊ณต
}
outputs_ft = model_finetuned.generate(pixel_values_ft, **generation_config_ft)
sequence_ft_raw = processor.batch_decode(outputs_ft.sequences)[0]
# print(f"\nFine-tuned Raw Output: {sequence_ft_raw}") # ์๋ฒ ๋ก๊ทธ์ ์ถ๋ ฅ (๋๋ฒ๊น
์ฉ)
# Fine-tuned ๋ชจ๋ธ ๊ฒฐ๊ณผ ํด๋ฆฌ๋
sequence_ft_cleaned = clean_sequence(sequence_ft_raw, processor, prompt_token_str=task_prompt_ft)
# print(f"Fine-tuned Cleaned Output: {sequence_ft_cleaned}") # ์๋ฒ ๋ก๊ทธ์ ์ถ๋ ฅ (๋๋ฒ๊น
์ฉ)
# ํด๋ฆฌ๋๋ ๊ฒฐ๊ณผ ํ์ฑ
result_json_ft = token2json_simple(sequence_ft_cleaned)
result_json_ft["raw_decoded_sequence_preview"] = sequence_ft_raw[:200] + "..." # ์๋ณธ ๊ฒฐ๊ณผ ํ๋ฆฌ๋ทฐ ์ถ๊ฐ
# ์ต์ข
JSON ๋ฌธ์์ด ๋ณํ
results_ft_json_str = json.dumps(result_json_ft, indent=2, ensure_ascii=False, sort_keys=False)
except Exception as e:
print(f"Error during fine-tuned model inference: {e}")
import traceback
traceback.print_exc() # detailed error log on server
results_ft_json_str = json.dumps({
"error": f"Fine-tuned ๋ชจ๋ธ ์ถ๋ก ์ค๋ฅ: {e}",
"raw_decoded_sequence_before_error": sequence_ft_raw
}, indent=2, ensure_ascii=False)
# === Base ๋ชจ๋ธ ์ถ๋ก ===
try:
pixel_values_base = processor_base(image, return_tensors="pt").pixel_values.to(device)
# Base ๋ชจ๋ธ์ฉ ํ๋กฌํํธ (์: <s_iitcdip> ๋๋ ๋ค๋ฅธ ์ผ๋ฐ ๋ฌธ์ ํ๋กฌํํธ)
# ์ฌ๊ธฐ์๋ ์ด์ ์ฝ๋์ ๋์ผํ๊ฒ <s_iitcdip> ์ฌ์ฉ
task_prompt_base = "<s_iitcdip>"
# Base ๋ชจ๋ธ์ ํด๋น ํ๋กฌํํธ ํ ํฐ์ด ์์ ์ ์์ผ๋ฏ๋ก ํ์ธ ๋๋ ๋ค๋ฅธ ํ๋กฌํํธ ์ฌ์ฉ ํ์
# ์ฌ๊ธฐ์๋ ์ผ๋จ ์งํ
try:
decoder_input_ids_base = processor_base.tokenizer(
task_prompt_base,
add_special_tokens=False,
return_tensors="pt",
).input_ids.to(device)
except Exception as tokenizer_e:
print(f"Warning: Base processor cannot tokenize prompt '{task_prompt_base}'. Using default generation. Error: {tokenizer_e}")
decoder_input_ids_base = None # ํ๋กฌํํธ ์์ด ์์ฑ
# ์์ฑ ํ๋ผ๋ฏธํฐ ์ค์
generation_config_base = {
"max_length": model_base.config.decoder.max_position_embeddings,
"early_stopping": True,
"pad_token_id": processor_base.tokenizer.pad_token_id,
"eos_token_id": processor_base.tokenizer.eos_token_id,
"use_cache": True,
"num_beams": 1, # Greedy decoding
"bad_words_ids": [[processor_base.tokenizer.unk_token_id]] if processor_base.tokenizer.unk_token_id else None,
"return_dict_in_generate": True,
}
# ํ๋กฌํํธ๊ฐ ์ฑ๊ณต์ ์ผ๋ก ์ธ์ฝ๋ฉ ๋์์ผ๋ฉด ์ถ๊ฐ
if decoder_input_ids_base is not None:
generation_config_base["decoder_input_ids"] = decoder_input_ids_base
outputs_base = model_base.generate(pixel_values_base, **generation_config_base)
sequence_base_raw = processor_base.batch_decode(outputs_base.sequences)[0]
# print(f"\nBase Raw Output: {sequence_base_raw}") # ์๋ฒ ๋ก๊ทธ์ ์ถ๋ ฅ (๋๋ฒ๊น
์ฉ)
# Base ๋ชจ๋ธ ๊ฒฐ๊ณผ ํด๋ฆฌ๋ (skip_special_tokens ์ฌ์ฉ)
sequence_base_cleaned = processor_base.batch_decode(outputs_base.sequences, skip_special_tokens=True)[0]
# print(f"Base Cleaned Output (skip_special_tokens): {sequence_base_cleaned}") # ์๋ฒ ๋ก๊ทธ์ ์ถ๋ ฅ (๋๋ฒ๊น
์ฉ)
# ๊ฒฐ๊ณผ ๋์
๋๋ฆฌ ์์ฑ
result_json_base = {
"raw_decoded_sequence_preview": sequence_base_raw[:200] + "...", # ์๋ณธ ๊ฒฐ๊ณผ ํ๋ฆฌ๋ทฐ
"output_skip_special_tokens": sequence_base_cleaned # ํด๋ฆฌ๋๋ ๊ฒฐ๊ณผ
}
# ์ต์ข
JSON ๋ฌธ์์ด ๋ณํ
results_base_json_str = json.dumps(result_json_base, indent=2, ensure_ascii=False, sort_keys=False)
except Exception as e:
print(f"Error during base model inference: {e}")
import traceback
traceback.print_exc() # detailed error log on server
results_base_json_str = json.dumps({
"error": f"Base ๋ชจ๋ธ ์ถ๋ก ์ค๋ฅ: {e}",
"raw_decoded_sequence_before_error": sequence_base_raw # Include raw if available
}, indent=2, ensure_ascii=False)
# ๋ ๋ชจ๋ธ์ ๊ฒฐ๊ณผ๋ฅผ JSON ๋ฌธ์์ด ํํ๋ก ๋ฐํ
return results_ft_json_str, results_base_json_str
# --- Gradio ์ธํฐํ์ด์ค ์ ์ ---
# CSS ์คํ์ผ ์ ์
custom_css = """
body { background-color: #f0f4f8; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
#main_title { text-align: center; color: #1a5276; font-size: 2.3em; font-weight: 600; margin-top: 20px; margin-bottom: 5px; }
#sub_description { text-align: center; color: #566573; font-size: 1.0em; margin-bottom: 25px; }
.gradio-container { border-radius: 10px !important; box-shadow: 0 3px 10px rgba(0,0,0,0.08); padding: 25px !important; }
footer { display: none !important; } /* Hide Gradio footer */
#output-title-ft, #output-title-base { color: #1a5276; font-weight: 600; margin-bottom: 8px; font-size: 1.2em; border-bottom: 2px solid #aed6f1; padding-bottom: 4px; }
#output_row > div.gradio-column { border: 1px solid #d5dbdb; padding: 15px !important; border-radius: 8px; background-color: #ffffff; margin: 0 8px !important; box-shadow: 0 1px 3px rgba(0,0,0,0.04); }
#json_output_ft > div:nth-child(2), #json_output_base > div:nth-child(2) { max-height: 600px; overflow-y: auto !important; } /* JSON output scroll */
"""
# Gradio Blocks ์ธํฐํ์ด์ค ๊ตฌ์ฑ
with gr.Blocks(css=custom_css, theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky")) as demo:
gr.Markdown("# Donut ๋ชจ๋ธ ๋น๊ต: Fine-tuned vs Base", elem_id="main_title")
gr.Markdown("์์์ฆ ์ด๋ฏธ์ง๋ฅผ ์
๋ก๋ํ๋ฉด Fine-tuned ๋ชจ๋ธ(SROIE ํ์ฑ)๊ณผ Base ๋ชจ๋ธ์ ์ถ์ถ ๊ฒฐ๊ณผ๋ฅผ ๋น๊ตํฉ๋๋ค.", elem_id="sub_description")
with gr.Row():
with gr.Column(scale=1):
image_input = gr.Image(type="numpy", label="๐งพ ์์์ฆ ์ด๋ฏธ์ง ์
๋ก๋")
submit_btn = gr.Button("๐ ๊ฒฐ๊ณผ ๋น๊ต ์์", variant="primary", scale=0)
# --- ์์ ์ด๋ฏธ์ง ๋ถ๋ถ์ Spaces ํ๊ฒฝ์์ ๊ฒฝ๋ก ๋ฌธ์ ๊ฐ ์์ ์ ์์ด ์ผ๋จ ์ฃผ์ ์ฒ๋ฆฌ ---
# ๋ง์ฝ ์์ ์ด๋ฏธ์ง๋ฅผ Space ์ ์ฅ์์ ํจ๊ป ์
๋ก๋ํ๊ณ ๊ฒฝ๋ก๋ฅผ ๋ง์ถ ์ ์๋ค๋ฉด ์ฃผ์ ํด์ ๊ฐ๋ฅ
example_img_dir = "example" # Space ์ ์ฅ์ ๋ฃจํธ์ ์๋ 'example' ํด๋ ์ง์
# list comprehension ์ฌ์ฉํ์ฌ ์กด์ฌํ๋ ํ์ผ๋ง ๋ชฉ๋ก์ผ๋ก ๋ง๋ฆ
example_paths = [os.path.join(example_img_dir, f) for f in ["1.jpg", "2.jpg"] if os.path.exists(os.path.join(example_img_dir, f))]
if example_paths:
gr.Examples(examples=example_paths, inputs=image_input, label="์์ ์ด๋ฏธ์ง ํด๋ฆญ (ํด๋ฆญ ํ '๊ฒฐ๊ณผ ๋น๊ต ์์' ๋ฒํผ ๋๋ฅด์ธ์)")
else:
gr.Markdown("_(์์ ์ด๋ฏธ์ง๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค. 'example' ํด๋ ํ์ธ ํ์)_")
with gr.Column(scale=2):
with gr.Row(elem_id="output_row"):
with gr.Column(scale=1):
gr.Markdown("### โจ Fine-tuned Model (SROIE ํ์ฑ)", elem_id="output-title-ft")
json_output_ft = gr.JSON(label="Fine-tuned ๊ฒฐ๊ณผ (JSON)", elem_id="json_output_ft")
with gr.Column(scale=1):
gr.Markdown("### ๐ก Base Model (Raw + Cleaned)", elem_id="output-title-base")
json_output_base = gr.JSON(label="Base ๋ชจ๋ธ ๊ฒฐ๊ณผ (JSON)", elem_id="json_output_base")
# ๋ฒํผ ํด๋ฆญ ์ ์คํํ ํจ์ ๋ฐ ์
์ถ๋ ฅ ์ ์
submit_btn.click(
fn=process_image_comparison,
inputs=image_input,
outputs=[json_output_ft, json_output_base] # ํจ์๊ฐ ๋ฐํํ๋ ์์๋๋ก ์ปดํฌ๋ํธ ์ง์
)
# --- Gradio ์ฑ ์คํ ---
# Hugging Face Spaces ์์ ์คํ๋ ๋๋ ์ด ๋ถ๋ถ์ด ํธ์ถ๋ฉ๋๋ค.
if __name__ == "__main__":
# share=True ๋ Spaces ํ๊ฒฝ์์๋ ํ์ ์์ต๋๋ค.
demo.launch() |