Spaces:
Sleeping
Sleeping
Download app.py from innkl24/Shan_Studio_App_Final: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/spaces/innkl24/Shan_Studio_App_Final/resolve/main/app.py
- Command line
-
hf download hf://spaces/innkl24/Shan_Studio_App_Final/app.py
-
curl -L -o app.py https://huggingface.co/spaces/innkl24/Shan_Studio_App_Final/resolve/main/app.py
11.6 kB
| # ======================================================= | |
| # File: app.py (v2.2 - Final Interactive Workflow) | |
| # ======================================================= | |
| import gradio as gr | |
| import torch | |
| import torch.nn as nn | |
| from pathlib import Path | |
| from itertools import groupby | |
| import albumentations as A | |
| from albumentations.pytorch import ToTensorV2 | |
| import cv2 | |
| import numpy as np | |
| from ultralytics import YOLO | |
| from PIL import Image | |
| import io | |
| import zipfile | |
| import json | |
| import pandas as pd | |
| import os | |
| # --- [1] นิยาม Class โมเดลและ Vocab (เหมือนเดิม) --- | |
| class ShanVocab: | |
| def __init__(self, file_path): | |
| with open(file_path, "r", encoding="utf-8") as f: | |
| char_list = list(f.read()) | |
| self.vocab = ["[BLANK]"] + sorted(list(set(char_list))) | |
| if "[UNK]" not in self.vocab: self.vocab.insert(1, "[UNK]") | |
| self.char_to_idx = {char: i for i, char in enumerate(self.vocab)} | |
| self.idx_to_char = {i: char for i, char in enumerate(self.vocab)} | |
| self.blank_idx = self.char_to_idx['[BLANK]'] | |
| def __len__(self): return len(self.vocab) | |
| class ShanCRNN(nn.Module): | |
| def __init__(self, num_chars): | |
| super().__init__(); self.cnn_p1=nn.Sequential(nn.Conv2d(3,64,3,1,1),nn.ReLU(True),nn.MaxPool2d(2,2)); self.cnn_p2=nn.Sequential(nn.Conv2d(64,128,3,1,1),nn.ReLU(True),nn.MaxPool2d(2,2)); self.cnn_p3=nn.Sequential(nn.Conv2d(128,256,3,1,1),nn.BatchNorm2d(256),nn.ReLU(True),nn.Conv2d(256,256,3,1,1),nn.ReLU(True),nn.MaxPool2d((2,2),(2,1),(0,1))); self.cnn_p4=nn.Sequential(nn.Conv2d(256,512,3,1,1),nn.BatchNorm2d(512),nn.ReLU(True),nn.Conv2d(512,512,3,1,1),nn.ReLU(True),nn.MaxPool2d((2,2),(2,1),(0,1))); self.cnn_p5=nn.Sequential(nn.Conv2d(512,512,kernel_size=(4,1),stride=1,padding=0),nn.BatchNorm2d(512),nn.ReLU(True)); self.lstm=nn.LSTM(512,256,bidirectional=True,num_layers=2,batch_first=True); self.output=nn.Linear(512,num_chars) | |
| def forward(self,x): x=self.cnn_p1(x);x=self.cnn_p2(x);x=self.cnn_p3(x);x=self.cnn_p4(x);x=self.cnn_p5(x); b,c,h,w=x.size();assert h==1; x=x.squeeze(2).permute(0,2,1); output,_=self.lstm(x); output=self.output(output); return output.permute(1,0,2) | |
| def ctc_decode(preds, idx_to_char_map, blank_idx): | |
| texts=[]; pred_indices=torch.argmax(preds.permute(1,0,2),dim=2) | |
| for indices in pred_indices: collapsed_indices=[k.item() for k,g in groupby(indices) if k.item()!=blank_idx]; texts.append("".join([idx_to_char_map.get(idx,"") for idx in collapsed_indices])) | |
| return texts | |
| # --- [2] โหลดโมเดลทั้ง 2 ตัว --- | |
| print("กำลังโหลดโมเดล AI ทั้ง 2 ตัว...") | |
| DEVICE = torch.device("cpu") | |
| detector_model = YOLO("best.onnx") | |
| vocab_handler = ShanVocab("vocab1.txt") | |
| ocr_model = ShanCRNN(num_chars=len(vocab_handler)) | |
| ocr_model.load_state_dict(torch.load("best_ocr_model_cer_0.0529.pth", map_location=DEVICE)) | |
| ocr_model.to(DEVICE) | |
| ocr_model.eval() | |
| print("✅ โมเดล AI ทั้ง 2 ตัวพร้อมใช้งาน!") | |
| # --- [3] สร้างฟังก์ชัน Helper --- | |
| ocr_transform = A.Compose([ A.Resize(height=64, width=400), A.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), ToTensorV2() ]) | |
| def predict_ocr(image_pil): | |
| image_np = np.array(image_pil.convert("RGB")) | |
| image_tensor = ocr_transform(image=image_np)["image"].unsqueeze(0).to(DEVICE) | |
| with torch.no_grad(): outputs = ocr_model(image_tensor).cpu() | |
| return ctc_decode(outputs, vocab_handler.idx_to_char, vocab_handler.blank_idx)[0] | |
| # --- [4] สร้างแอปพลิเคชัน Gradio --- | |
| with gr.Blocks(theme=gr.themes.Soft(), css="footer {display: none !important}") as demo: | |
| gr.Markdown("# สตูดิโอ Flywheel สร้างข้อมูล OCR v2.2") | |
| # State management | |
| uploaded_file_paths = gr.State([]) | |
| # 🔹 *** [แก้ไข] ชื่อตัวแปรที่ถูกต้อง *** 🔹 | |
| processed_data = gr.State({}) | |
| with gr.Row(): | |
| file_upload = gr.File(label="1. อัปโหลดรูปภาพทั้งหมด", file_count="multiple", file_types=["image"]) | |
| with gr.Row(): | |
| file_dropdown = gr.Dropdown(label="2. เลือกรูปภาพที่จะทำงาน", interactive=True) | |
| process_btn = gr.Button("ประมวลผลรูปภาพนี้", variant="primary") | |
| gr.Markdown("---") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("### รูปต้นฉบับพร้อมกรอบที่ AI หาเจอ") | |
| debug_image = gr.Image(label="Debug View", interactive=False) | |
| with gr.Column(scale=1): | |
| gr.Markdown("### แก้ไขข้อความที่ AI อ่านได้") | |
| dataframe_output = gr.Dataframe(headers=["ข้อความกำกับ"], col_count=(1, "fixed"), type="pandas", interactive=True) | |
| gr.Markdown("---") | |
| with gr.Tabs(): | |
| with gr.TabItem("💾 ดาวน์โหลด Dataset"): | |
| with gr.Row(): | |
| export_ocr_btn = gr.Button("ดาวน์โหลด Dataset (OCR)") | |
| export_yolo_btn = gr.Button("ดาวน์โหลด Dataset (YOLO)") | |
| output_file = gr.File(label="ไฟล์ Dataset (.zip)") | |
| # --- ฟังก์ชันการทำงาน --- | |
| def store_uploaded_files(files): | |
| if not files: | |
| return [], gr.Dropdown.update(choices=[], value=None) | |
| file_paths = [f.name for f in files] | |
| filenames = [os.path.basename(p) for p in file_paths] | |
| return file_paths, gr.Dropdown.update(choices=filenames, value=filenames[0]) | |
| def process_single_image(selected_filename, all_file_paths_state, current_processed_data): | |
| if not selected_filename or not all_file_paths_state: | |
| return None, pd.DataFrame(), current_processed_data | |
| filepath = next((f for f in all_file_paths_state if os.path.basename(f) == selected_filename), None) | |
| if not filepath: | |
| raise gr.Error(f"ไม่พบไฟล์ {selected_filename} ในรายการที่อัปโหลด") | |
| original_image = Image.open(filepath).convert("RGB") | |
| img_np_bgr = cv2.cvtColor(np.array(original_image), cv2.COLOR_RGB2BGR) | |
| results = detector_model(original_image, verbose=False) | |
| boxes = results[0].boxes.xyxy.cpu().numpy() | |
| sorted_boxes = sorted(boxes, key=lambda box: box[1]) | |
| ocr_texts = [] | |
| lines_data = [] | |
| for box in sorted_boxes: | |
| x1, y1, x2, y2 = map(int, box) | |
| cv2.rectangle(img_np_bgr, (x1, y1), (x2, y2), (0, 0, 255), 2) | |
| if (x2 - x1) > 5 and (y2 - y1) > 5: | |
| cropped_pil = original_image.crop((x1, y1, x2, y2)) | |
| predicted_text = predict_ocr(cropped_pil) | |
| ocr_texts.append([predicted_text]) | |
| lines_data.append({"text": predicted_text, "box": [x1, y1, x2, y2]}) | |
| current_processed_data[selected_filename] = { "lines": lines_data, "image_size": original_image.size } | |
| df = pd.DataFrame(ocr_texts, columns=["ข้อความกำกับ"]) | |
| debug_img_rgb = cv2.cvtColor(img_np_bgr, cv2.COLOR_BGR2RGB) | |
| return debug_img_rgb, df, current_processed_data | |
| def update_processed_data(df, selected_filename, current_processed_data): | |
| if selected_filename and selected_filename in current_processed_data: | |
| lines = current_processed_data[selected_filename]["lines"] | |
| for i, line in enumerate(lines): | |
| if i < len(df): | |
| lines[i]["text"] = df.iloc[i, 0] | |
| return current_processed_data | |
| def export_ocr_dataset(processed_data_state, all_file_paths_state): | |
| if not processed_data_state: raise gr.Error("ไม่มีข้อมูลให้ดาวน์โหลด!") | |
| image_dict = {os.path.basename(f): Image.open(f).convert("RGB") for f in all_file_paths_state} | |
| buffer = io.BytesIO() | |
| with zipfile.ZipFile(buffer, 'w') as zf: | |
| labels = [] | |
| img_folder = "images/" | |
| counter = 1 | |
| for filename, data in processed_data_state.items(): | |
| original_image = image_dict.get(filename) | |
| if not original_image: continue | |
| for line in data["lines"]: | |
| text = line["text"] | |
| if text and text.strip(): | |
| new_filename = f"line_{counter:06d}.png" | |
| x1, y1, x2, y2 = line["box"] | |
| cropped_pil = original_image.crop((x1, y1, x2, y2)) | |
| img_byte_arr = io.BytesIO() | |
| cropped_pil.save(img_byte_arr, format='PNG') | |
| zf.writestr(img_folder + new_filename, img_byte_arr.getvalue()) | |
| labels.append(f"{new_filename}\t{text}") | |
| counter += 1 | |
| zf.writestr("labels.txt", "\n".join(labels)) | |
| buffer.seek(0) | |
| return gr.File.update(value=buffer, visible=True, label="ดาวน์โหลดไฟล์ OCR") | |
| def export_yolo_dataset(processed_data_state, all_file_paths_state): | |
| if not processed_data_state: raise gr.Error("ไม่มีข้อมูลให้ดาวน์โหลด!") | |
| image_dict = {os.path.basename(f): Image.open(f).convert("RGB") for f in all_file_paths_state} | |
| buffer = io.BytesIO() | |
| with zipfile.ZipFile(buffer, 'w') as zf: | |
| for filename, data in processed_data_state.items(): | |
| original_image = image_dict.get(filename) | |
| if not original_image: continue | |
| img_byte_arr = io.BytesIO() | |
| original_image.save(img_byte_arr, format='PNG') | |
| zf.writestr(f"images/{filename}", img_byte_arr.getvalue()) | |
| w, h = data["image_size"] | |
| yolo_strings = [] | |
| for line in data["lines"]: | |
| x1, y1, x2, y2 = line["box"] | |
| x_center=(x1+x2)/2/w; y_center=(y1+y2)/2/h | |
| width=(x2-x1)/w; height=(y2-y1)/h | |
| yolo_strings.append(f"0 {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}") | |
| label_filename = Path(filename).stem + ".txt" | |
| zf.writestr(f"labels/{label_filename}", "\n".join(yolo_strings)) | |
| buffer.seek(0) | |
| return gr.File.update(value=buffer, visible=True, label="ดาวน์โหลดไฟล์ YOLO") | |
| # --- เชื่อมต่อ Component --- | |
| file_upload.upload(store_uploaded_files, inputs=[file_upload], outputs=[uploaded_file_paths, file_dropdown]) | |
| # 🔹 *** [แก้ไข] ชื่อตัวแปรที่ถูกต้อง *** 🔹 | |
| process_btn.click(process_single_image, inputs=[file_dropdown, uploaded_file_paths, processed_data], outputs=[debug_image, dataframe_output, processed_data]) | |
| dataframe_output.change(update_processed_data, inputs=[dataframe_output, file_dropdown, processed_data], outputs=[processed_data]) | |
| export_ocr_btn.click(export_ocr_dataset, inputs=[processed_data, uploaded_file_paths], outputs=[output_file]) | |
| export_yolo_btn.click(export_yolo_dataset, inputs=[processed_data, uploaded_file_paths], outputs=[output_file]) | |
| demo.queue().launch(debug=True) |