Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,49 +1,88 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
| 2 |
from PIL import Image
|
| 3 |
-
|
| 4 |
from huggingface_hub import snapshot_download
|
| 5 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
# Load
|
| 8 |
-
def load_labels(
|
| 9 |
-
with open(
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
predicted_chars.append(char)
|
| 32 |
-
|
| 33 |
-
# Join predictions as text
|
| 34 |
-
prediction_text = ''.join(predicted_chars)
|
| 35 |
-
|
| 36 |
-
return prediction_text
|
| 37 |
-
|
| 38 |
-
# Setup
|
| 39 |
REPO_ID = "JJJHHHH/CCR_EthicalSplit_Finetune"
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
# Gradio
|
| 46 |
gr.Interface(fn=predict,
|
| 47 |
-
inputs=gr.Image(type="pil"),
|
| 48 |
-
outputs=gr.
|
| 49 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
from PIL import Image
|
| 6 |
+
from torchvision import models, transforms
|
| 7 |
from huggingface_hub import snapshot_download
|
| 8 |
+
import gradio as gr
|
| 9 |
+
|
| 10 |
+
# Model Architecture
|
| 11 |
+
class ChineseClassifier(nn.Module):
|
| 12 |
+
def __init__(self, embed_dim, num_classes, pretrainedEncoder=True, unfreezeEncoder=True):
|
| 13 |
+
super().__init__()
|
| 14 |
+
resnet = models.resnet50(weights=models.ResNet50_Weights.DEFAULT if pretrainedEncoder else None)
|
| 15 |
+
self.resnet = nn.Sequential(*list(resnet.children())[:-1])
|
| 16 |
+
for param in self.resnet.parameters():
|
| 17 |
+
param.requires_grad = unfreezeEncoder
|
| 18 |
+
self.fc = nn.Linear(resnet.fc.in_features, embed_dim)
|
| 19 |
+
self.batch_norm = nn.BatchNorm1d(embed_dim)
|
| 20 |
+
self.dropout = nn.Dropout(0.3)
|
| 21 |
+
self.classifier = nn.Linear(embed_dim, num_classes)
|
| 22 |
+
|
| 23 |
+
def forward(self, x, return_embedding=False):
|
| 24 |
+
x = self.resnet(x)
|
| 25 |
+
x = torch.flatten(x, 1)
|
| 26 |
+
x = self.fc(x)
|
| 27 |
+
x = self.batch_norm(x)
|
| 28 |
+
x = self.dropout(x)
|
| 29 |
+
if return_embedding:
|
| 30 |
+
return x
|
| 31 |
+
x = self.classifier(x)
|
| 32 |
+
return x
|
| 33 |
|
| 34 |
+
# Load labels.json
|
| 35 |
+
def load_labels(labels_path):
|
| 36 |
+
with open(labels_path, "r", encoding="utf-8") as f:
|
| 37 |
+
labels = json.load(f)
|
| 38 |
+
return labels
|
| 39 |
+
|
| 40 |
+
# Transform for inference
|
| 41 |
+
def prepare_transforms():
|
| 42 |
+
return transforms.Compose([
|
| 43 |
+
transforms.Resize((224, 224)),
|
| 44 |
+
transforms.ToTensor(),
|
| 45 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
| 46 |
+
std=[0.229, 0.224, 0.225]),
|
| 47 |
+
])
|
| 48 |
+
|
| 49 |
+
# Load Model
|
| 50 |
+
def load_model(model_path, embed_dim, num_classes, device):
|
| 51 |
+
model = ChineseClassifier(embed_dim, num_classes).to(device)
|
| 52 |
+
checkpoint = torch.load(model_path, map_location=device)
|
| 53 |
+
model.load_state_dict(checkpoint)
|
| 54 |
+
model.eval()
|
| 55 |
+
return model
|
| 56 |
+
|
| 57 |
+
# HF snapshot + model init
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
REPO_ID = "JJJHHHH/CCR_EthicalSplit_Finetune"
|
| 59 |
+
snapshot_dir = snapshot_download(repo_id=REPO_ID)
|
| 60 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 61 |
+
|
| 62 |
+
labels_path = os.path.join(snapshot_dir, "enhancedLabels.json")
|
| 63 |
+
model_path = os.path.join(snapshot_dir, "CCR_EthicalSplit_Finetune.pth")
|
| 64 |
+
|
| 65 |
+
labels = load_labels(labels_path)
|
| 66 |
+
idx_to_class = sorted(set(labels.values()))
|
| 67 |
+
class_names = idx_to_class
|
| 68 |
+
|
| 69 |
+
model = load_model(model_path, embed_dim=512, num_classes=len(class_names), device=device)
|
| 70 |
+
transform = prepare_transforms()
|
| 71 |
|
| 72 |
+
# Inference
|
| 73 |
+
def predict(image: Image.Image):
|
| 74 |
+
image = image.convert("RGB")
|
| 75 |
+
input_tensor = transform(image).unsqueeze(0).to(device)
|
| 76 |
+
with torch.no_grad():
|
| 77 |
+
output = model(input_tensor)
|
| 78 |
+
pred_idx = output.argmax(dim=1).item()
|
| 79 |
+
pred_class = class_names[pred_idx]
|
| 80 |
+
return f"Prediction: {pred_class}"
|
| 81 |
|
| 82 |
+
# Gradio Interface
|
| 83 |
gr.Interface(fn=predict,
|
| 84 |
+
inputs=gr.Image(type="pil", label="Upload Calligraphy Image"),
|
| 85 |
+
outputs=gr.Text(label="Prediction"),
|
| 86 |
+
title="Chinese Calligraphy Classifier",
|
| 87 |
+
description="Upload an image of handwritten Chinese text. The model will classify the character."
|
| 88 |
+
).launch()
|