Update app.py
Browse files
app.py
CHANGED
|
@@ -19,32 +19,48 @@ parseq_path = os.path.join(os.path.dirname(__file__), 'parseq')
|
|
| 19 |
if os.path.exists(parseq_path):
|
| 20 |
sys.path.insert(0, parseq_path)
|
| 21 |
else:
|
| 22 |
-
logger.
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
from strhub.data.utils import Tokenizer
|
| 26 |
import torch.hub
|
| 27 |
|
| 28 |
warnings.filterwarnings('ignore')
|
| 29 |
|
| 30 |
# =========================
|
| 31 |
-
# Configuration
|
| 32 |
# =========================
|
|
|
|
|
|
|
| 33 |
ORIYA_CHARSET = "ଅଆଇଈଉଊଋଌଏଐଓଔକଖଗଘଙଚଛଜଝଞଟଠଡଢଣତଥଦଧନପଫବଭମଯରଲଳଵଶଷସହାିିୀୁୂୃୄେୈୋୌ୍ଂଁଃ"
|
| 34 |
|
| 35 |
LANGUAGES = {
|
| 36 |
"Telugu": {
|
| 37 |
"model_path": "parseq_telugu_finetuned_final_5epochs.pth",
|
| 38 |
"samples_dir": "telugu_samples",
|
|
|
|
| 39 |
},
|
| 40 |
"Bengali": {
|
| 41 |
"model_path": "finetuned_bengali_model.pth",
|
| 42 |
"samples_dir": "bengali_samples",
|
|
|
|
| 43 |
},
|
| 44 |
"Oriya": {
|
| 45 |
"model_path": "parseq_oriya_final_direct.pth",
|
| 46 |
"samples_dir": "oriya_samples",
|
| 47 |
-
"charset": ORIYA_CHARSET
|
| 48 |
}
|
| 49 |
}
|
| 50 |
|
|
@@ -82,26 +98,40 @@ def load_model(model_path, lang_name):
|
|
| 82 |
return model_cache[cache_key]
|
| 83 |
|
| 84 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
|
| 85 |
|
| 86 |
if not os.path.exists(model_path):
|
| 87 |
logger.error(f"Model not found: {model_path}")
|
| 88 |
return None, None, None
|
| 89 |
|
| 90 |
try:
|
| 91 |
-
# Load checkpoint with weights_only=False for compatibility
|
| 92 |
checkpoint = torch.load(model_path, map_location='cpu', weights_only=False)
|
|
|
|
| 93 |
|
|
|
|
| 94 |
if 'charset' in checkpoint:
|
| 95 |
charset_str = checkpoint['charset']
|
| 96 |
-
|
| 97 |
-
charset_str = ORIYA_CHARSET
|
| 98 |
else:
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
# Handle different checkpoint formats
|
| 107 |
if 'model_state_dict' in checkpoint:
|
|
@@ -111,43 +141,59 @@ def load_model(model_path, lang_name):
|
|
| 111 |
else:
|
| 112 |
state_dict = checkpoint
|
| 113 |
|
| 114 |
-
# Remove
|
| 115 |
new_state_dict = {}
|
| 116 |
for k, v in state_dict.items():
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
new_state_dict[k] = v
|
| 120 |
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
model = model.to(device)
|
| 123 |
model.eval()
|
| 124 |
|
| 125 |
-
model_cache[cache_key] = (model, device,
|
| 126 |
-
logger.info(f"Loaded {lang_name} model successfully")
|
| 127 |
-
return model, device,
|
| 128 |
|
| 129 |
except Exception as e:
|
| 130 |
logger.error(f"Error loading {lang_name}: {e}")
|
|
|
|
|
|
|
| 131 |
return None, None, None
|
| 132 |
|
| 133 |
# =========================
|
| 134 |
# Inference
|
| 135 |
# =========================
|
| 136 |
def inference_image(model, image, device, tokenizer):
|
| 137 |
-
|
| 138 |
-
image =
|
|
|
|
| 139 |
|
| 140 |
-
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
|
| 150 |
-
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
# =========================
|
| 153 |
# Get samples for specific language
|
|
|
|
| 19 |
if os.path.exists(parseq_path):
|
| 20 |
sys.path.insert(0, parseq_path)
|
| 21 |
else:
|
| 22 |
+
logger.warning(f"PARSeq folder not found at {parseq_path}, trying direct import")
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
from strhub.data.utils import Tokenizer
|
| 26 |
+
except ImportError:
|
| 27 |
+
logger.error("Failed to import Tokenizer. Make sure PARSeq is installed.")
|
| 28 |
+
# Create a basic tokenizer if PARSeq is not available
|
| 29 |
+
class Tokenizer:
|
| 30 |
+
def __init__(self, charset):
|
| 31 |
+
self.charset = charset
|
| 32 |
+
self._itos = {i: ch for i, ch in enumerate(charset)}
|
| 33 |
+
self._stoi = {ch: i for i, ch in enumerate(charset)}
|
| 34 |
+
self.pad_id = 0
|
| 35 |
+
self.bos_id = 1
|
| 36 |
+
self.eos_id = 2
|
| 37 |
|
|
|
|
| 38 |
import torch.hub
|
| 39 |
|
| 40 |
warnings.filterwarnings('ignore')
|
| 41 |
|
| 42 |
# =========================
|
| 43 |
+
# Configuration - Added explicit charsets for all languages
|
| 44 |
# =========================
|
| 45 |
+
TELUGU_CHARSET = "అఆఇఈఉఊఋఌఎఏఐఒఓఔకఖగఘఙచఛజఝఞటఠడఢణతథదధనపఫబభమయరఱలళవశషసహాిీుూృౄెేైొోౌ్ౢౣ"
|
| 46 |
+
BENGALI_CHARSET = "অআইঈউঊঋএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহাািীুূৃৄেৈোৌ্ৎংঃ"
|
| 47 |
ORIYA_CHARSET = "ଅଆଇଈଉଊଋଌଏଐଓଔକଖଗଘଙଚଛଜଝଞଟଠଡଢଣତଥଦଧନପଫବଭମଯରଲଳଵଶଷସହାିିୀୁୂୃୄେୈୋୌ୍ଂଁଃ"
|
| 48 |
|
| 49 |
LANGUAGES = {
|
| 50 |
"Telugu": {
|
| 51 |
"model_path": "parseq_telugu_finetuned_final_5epochs.pth",
|
| 52 |
"samples_dir": "telugu_samples",
|
| 53 |
+
"charset": TELUGU_CHARSET
|
| 54 |
},
|
| 55 |
"Bengali": {
|
| 56 |
"model_path": "finetuned_bengali_model.pth",
|
| 57 |
"samples_dir": "bengali_samples",
|
| 58 |
+
"charset": BENGALI_CHARSET
|
| 59 |
},
|
| 60 |
"Oriya": {
|
| 61 |
"model_path": "parseq_oriya_final_direct.pth",
|
| 62 |
"samples_dir": "oriya_samples",
|
| 63 |
+
"charset": ORIYA_CHARSET
|
| 64 |
}
|
| 65 |
}
|
| 66 |
|
|
|
|
| 98 |
return model_cache[cache_key]
|
| 99 |
|
| 100 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 101 |
+
logger.info(f"Loading {lang_name} model on {device}")
|
| 102 |
|
| 103 |
if not os.path.exists(model_path):
|
| 104 |
logger.error(f"Model not found: {model_path}")
|
| 105 |
return None, None, None
|
| 106 |
|
| 107 |
try:
|
| 108 |
+
# Load checkpoint with weights_only=False for compatibility
|
| 109 |
checkpoint = torch.load(model_path, map_location='cpu', weights_only=False)
|
| 110 |
+
logger.info(f"Checkpoint loaded for {lang_name}")
|
| 111 |
|
| 112 |
+
# Get charset - first try from checkpoint, then from config
|
| 113 |
if 'charset' in checkpoint:
|
| 114 |
charset_str = checkpoint['charset']
|
| 115 |
+
logger.info(f"Using charset from checkpoint for {lang_name}")
|
|
|
|
| 116 |
else:
|
| 117 |
+
charset_str = LANGUAGES[lang_name].get('charset')
|
| 118 |
+
if charset_str:
|
| 119 |
+
logger.info(f"Using configured charset for {lang_name}")
|
| 120 |
+
else:
|
| 121 |
+
logger.error(f"No charset found for {lang_name}")
|
| 122 |
+
return None, None, None
|
| 123 |
|
| 124 |
+
# Load model architecture
|
| 125 |
+
try:
|
| 126 |
+
model = torch.hub.load('baudm/parseq', 'parseq', pretrained=False, trust_repo=True)
|
| 127 |
+
logger.info(f"Model architecture loaded for {lang_name}")
|
| 128 |
+
except Exception as e:
|
| 129 |
+
logger.error(f"Failed to load model architecture: {e}")
|
| 130 |
+
return None, None, None
|
| 131 |
+
|
| 132 |
+
# Create tokenizer and attach to model
|
| 133 |
+
tokenizer = Tokenizer(charset_str)
|
| 134 |
+
model.tokenizer = tokenizer
|
| 135 |
|
| 136 |
# Handle different checkpoint formats
|
| 137 |
if 'model_state_dict' in checkpoint:
|
|
|
|
| 141 |
else:
|
| 142 |
state_dict = checkpoint
|
| 143 |
|
| 144 |
+
# Remove 'module.' prefix if present and handle other key issues
|
| 145 |
new_state_dict = {}
|
| 146 |
for k, v in state_dict.items():
|
| 147 |
+
# Remove 'module.' prefix
|
| 148 |
+
if k.startswith('module.'):
|
| 149 |
+
k = k[7:]
|
| 150 |
+
# Handle other common prefixes
|
| 151 |
+
if k.startswith('_orig_mod.'):
|
| 152 |
+
k = k[10:]
|
| 153 |
new_state_dict[k] = v
|
| 154 |
|
| 155 |
+
# Load state dict with strict=False to handle missing/unexpected keys
|
| 156 |
+
missing_keys, unexpected_keys = model.load_state_dict(new_state_dict, strict=False)
|
| 157 |
+
if missing_keys:
|
| 158 |
+
logger.warning(f"Missing keys for {lang_name}: {missing_keys[:5]}...")
|
| 159 |
+
if unexpected_keys:
|
| 160 |
+
logger.warning(f"Unexpected keys for {lang_name}: {unexpected_keys[:5]}...")
|
| 161 |
+
|
| 162 |
model = model.to(device)
|
| 163 |
model.eval()
|
| 164 |
|
| 165 |
+
model_cache[cache_key] = (model, device, tokenizer)
|
| 166 |
+
logger.info(f"✅ Loaded {lang_name} model successfully")
|
| 167 |
+
return model, device, tokenizer
|
| 168 |
|
| 169 |
except Exception as e:
|
| 170 |
logger.error(f"Error loading {lang_name}: {e}")
|
| 171 |
+
import traceback
|
| 172 |
+
traceback.print_exc()
|
| 173 |
return None, None, None
|
| 174 |
|
| 175 |
# =========================
|
| 176 |
# Inference
|
| 177 |
# =========================
|
| 178 |
def inference_image(model, image, device, tokenizer):
|
| 179 |
+
try:
|
| 180 |
+
if image.mode != 'RGB':
|
| 181 |
+
image = image.convert('RGB')
|
| 182 |
|
| 183 |
+
img_tensor = transform(image).unsqueeze(0).to(device)
|
| 184 |
|
| 185 |
+
with torch.no_grad():
|
| 186 |
+
logits = model(img_tensor)
|
| 187 |
+
predicted_text = decode_prediction(logits, tokenizer)
|
| 188 |
|
| 189 |
+
probs = torch.softmax(logits, dim=-1)
|
| 190 |
+
max_probs = probs.max(dim=-1)[0][0]
|
| 191 |
+
avg_conf = max_probs[:len(predicted_text)].mean().item() if len(predicted_text) > 0 else 0
|
| 192 |
|
| 193 |
+
return predicted_text, avg_conf
|
| 194 |
+
except Exception as e:
|
| 195 |
+
logger.error(f"Inference error: {e}")
|
| 196 |
+
return "", 0.0
|
| 197 |
|
| 198 |
# =========================
|
| 199 |
# Get samples for specific language
|