G-Madhuri commited on
Commit
d6376a9
·
verified ·
1 Parent(s): 8479701

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -57
app.py CHANGED
@@ -34,44 +34,25 @@ except ImportError:
34
  raise
35
  except ImportError as e:
36
  logger.error(f"Failed to import PARSeq: {e}")
37
- # Create placeholder classes
38
- class Tokenizer:
39
- def __init__(self, charset):
40
- self.charset = charset
41
- self._itos = {i: ch for i, ch in enumerate(charset)}
42
- self._stoi = {ch: i for i, ch in enumerate(charset)}
43
- self.pad_id = 0
44
- self.bos_id = 1
45
- self.eos_id = 2
46
-
47
- class PARSeq:
48
- def __init__(self, *args, **kwargs):
49
- pass
50
 
51
  warnings.filterwarnings('ignore')
52
 
53
  # =========================
54
- # Configuration - Added explicit charsets for all languages
55
  # =========================
56
- TELUGU_CHARSET = "అఆఇఈఉఊఋఌఎఏఐఒఓఔకఖగఘఙచఛజఝఞటఠడఢణతథదధనపఫబభమయరఱలళవశషసహాిీుూృౄెేైొోౌ్ౢౣ"
57
- BENGALI_CHARSET = "অআইঈউঊঋএঐওঔকখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহাািীুূৃৄেৈোৌ্ৎংঃ"
58
- ORIYA_CHARSET = "ଅଆଇଈଉଊଋଌଏଐଓଔକଖଗଘଙଚଛଜଝଞଟଠଡଢଣତଥଦଧନପଫବଭମଯରଲଳଵଶଷସହାିିୀୁୂୃୄେୈୋୌ୍ଂଁଃ"
59
-
60
  LANGUAGES = {
61
  "Telugu": {
62
  "model_path": "parseq_telugu_finetuned_final_5epochs.pth",
63
  "samples_dir": "telugu_samples",
64
- "charset": TELUGU_CHARSET
65
  },
66
  "Bengali": {
67
  "model_path": "finetuned_bengali_model.pth",
68
  "samples_dir": "bengali_samples",
69
- "charset": BENGALI_CHARSET
70
  },
71
  "Oriya": {
72
  "model_path": "parseq_oriya_final_direct.pth",
73
  "samples_dir": "oriya_samples",
74
- "charset": ORIYA_CHARSET
75
  }
76
  }
77
 
@@ -116,39 +97,28 @@ def load_model(model_path, lang_name):
116
  return None, None, None
117
 
118
  try:
119
- # Load checkpoint with weights_only=False for compatibility
120
  checkpoint = torch.load(model_path, map_location='cpu', weights_only=False)
121
  logger.info(f"Checkpoint loaded for {lang_name}")
122
 
123
- # Get charset - first try from checkpoint, then from config
124
- if 'charset' in checkpoint:
125
- charset_str = checkpoint['charset']
126
- logger.info(f"Using charset from checkpoint for {lang_name}")
127
- else:
128
- charset_str = LANGUAGES[lang_name].get('charset')
129
- if charset_str:
130
- logger.info(f"Using configured charset for {lang_name}")
131
- else:
132
- logger.error(f"No charset found for {lang_name}")
133
- return None, None, None
134
 
135
  # Create tokenizer
136
  tokenizer = Tokenizer(charset_str)
137
 
138
- # Create model instance - use PARSeq class directly
139
- try:
140
- # Try to create model with proper arguments
141
- model = PARSeq(
142
- charset_size=len(charset_str),
143
- img_size=(32, 128),
144
- max_label_length=100
145
- )
146
- logger.info(f"Model instance created for {lang_name}")
147
- except Exception as e:
148
- logger.error(f"Failed to create model instance: {e}")
149
- return None, None, None
150
-
151
- # Handle different checkpoint formats
152
  if 'model_state_dict' in checkpoint:
153
  state_dict = checkpoint['model_state_dict']
154
  elif 'model' in checkpoint:
@@ -156,25 +126,24 @@ def load_model(model_path, lang_name):
156
  else:
157
  state_dict = checkpoint
158
 
159
- # Remove 'module.' prefix if present and handle other key issues
160
  new_state_dict = {}
161
  for k, v in state_dict.items():
162
- # Remove 'module.' prefix
163
  if k.startswith('module.'):
164
  k = k[7:]
165
- # Handle other common prefixes
166
  if k.startswith('_orig_mod.'):
167
  k = k[10:]
168
  new_state_dict[k] = v
169
 
170
- # Load state dict with strict=False to handle missing/unexpected keys
171
- missing_keys, unexpected_keys = model.load_state_dict(new_state_dict, strict=False)
172
- if missing_keys:
173
- logger.warning(f"Missing keys for {lang_name}: {missing_keys[:5]}...")
174
- if unexpected_keys:
175
- logger.warning(f"Unexpected keys for {lang_name}: {unexpected_keys[:5]}...")
176
 
177
- model.tokenizer = tokenizer
178
  model = model.to(device)
179
  model.eval()
180
 
 
34
  raise
35
  except ImportError as e:
36
  logger.error(f"Failed to import PARSeq: {e}")
37
+ exit()
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  warnings.filterwarnings('ignore')
40
 
41
  # =========================
42
+ # Configuration
43
  # =========================
 
 
 
 
44
  LANGUAGES = {
45
  "Telugu": {
46
  "model_path": "parseq_telugu_finetuned_final_5epochs.pth",
47
  "samples_dir": "telugu_samples",
 
48
  },
49
  "Bengali": {
50
  "model_path": "finetuned_bengali_model.pth",
51
  "samples_dir": "bengali_samples",
 
52
  },
53
  "Oriya": {
54
  "model_path": "parseq_oriya_final_direct.pth",
55
  "samples_dir": "oriya_samples",
 
56
  }
57
  }
58
 
 
97
  return None, None, None
98
 
99
  try:
100
+ # Load checkpoint
101
  checkpoint = torch.load(model_path, map_location='cpu', weights_only=False)
102
  logger.info(f"Checkpoint loaded for {lang_name}")
103
 
104
+ # Get charset from checkpoint (since you saved models with charset)
105
+ if 'charset' not in checkpoint:
106
+ logger.error(f"No charset found in checkpoint for {lang_name}")
107
+ return None, None, None
108
+
109
+ charset_str = checkpoint['charset']
110
+ logger.info(f"Charset length for {lang_name}: {len(charset_str)}")
 
 
 
 
111
 
112
  # Create tokenizer
113
  tokenizer = Tokenizer(charset_str)
114
 
115
+ # Load the pretrained model from torch hub (this works!)
116
+ model = torch.hub.load('baudm/parseq', 'parseq', pretrained=True, trust_repo=True)
117
+
118
+ # Modify the tokenizer
119
+ model.tokenizer = tokenizer
120
+
121
+ # Now load your fine-tuned weights
 
 
 
 
 
 
 
122
  if 'model_state_dict' in checkpoint:
123
  state_dict = checkpoint['model_state_dict']
124
  elif 'model' in checkpoint:
 
126
  else:
127
  state_dict = checkpoint
128
 
129
+ # Clean up state dict keys
130
  new_state_dict = {}
131
  for k, v in state_dict.items():
132
+ # Remove 'module.' prefix if present
133
  if k.startswith('module.'):
134
  k = k[7:]
135
+ # Remove '_orig_mod.' prefix if present
136
  if k.startswith('_orig_mod.'):
137
  k = k[10:]
138
  new_state_dict[k] = v
139
 
140
+ # Load weights
141
+ missing, unexpected = model.load_state_dict(new_state_dict, strict=False)
142
+ if missing:
143
+ logger.warning(f"Missing keys: {missing[:5]}...")
144
+ if unexpected:
145
+ logger.warning(f"Unexpected keys: {unexpected[:5]}...")
146
 
 
147
  model = model.to(device)
148
  model.eval()
149