JJJHHHH commited on
Commit
b5c1972
·
verified ·
1 Parent(s): 0cb7f53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -42
app.py CHANGED
@@ -1,49 +1,88 @@
1
- from ultralytics import YOLO
 
 
 
2
  from PIL import Image
3
- import gradio as gr
4
  from huggingface_hub import snapshot_download
5
- import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # Load label map from labels.txt
8
- def load_labels(label_path="labels.txt"):
9
- with open(label_path, "r", encoding="utf-8") as f:
10
- lines = f.read().splitlines()
11
- id2char = {i: char for i, char in enumerate(lines)}
12
- return id2char
13
-
14
- # Load model from HuggingFace
15
- def load_model(repo_id):
16
- download_dir = snapshot_download(repo_id)
17
- path = os.path.join(download_dir, "CCR_EthicalSplit_Finetune.pth")
18
- detection_model = YOLO(path, task='detect')
19
- return detection_model
20
-
21
- # Prediction function
22
- def predict(pilimg):
23
- results = detection_model.predict(pilimg, conf=0.5, iou=0.6)
24
- result = results[0]
25
-
26
- # Extract predicted classes
27
- predicted_chars = []
28
- for box in result.boxes:
29
- cls_idx = int(box.cls.item())
30
- char = id2char.get(cls_idx, '?')
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
- LABEL_PATH = "labels.txt"
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- id2char = load_labels(LABEL_PATH)
43
- detection_model = load_model(REPO_ID)
 
 
 
 
 
 
 
44
 
45
- # Gradio interface (image in, text out)
46
  gr.Interface(fn=predict,
47
- inputs=gr.Image(type="pil"),
48
- outputs=gr.Textbox(label="Predicted Chinese Text")
49
- ).launch(share=True)
 
 
 
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()