Brian045 commited on
Commit
34a4572
·
verified ·
1 Parent(s): 1864950

Update translator_utils.py

Browse files
Files changed (1) hide show
  1. translator_utils.py +56 -33
translator_utils.py CHANGED
@@ -2,7 +2,7 @@ import os
2
  import pandas as pd
3
  from transformers import pipeline
4
  import torch
5
- from huggingface_hub import HfApi
6
  import spacy
7
  from spacy.lang.en import English
8
 
@@ -21,6 +21,7 @@ _nlp = None
21
  def download_dataset(force=False):
22
  """
23
  Downloads the dataset if it doesn't exist locally or if forced.
 
24
  """
25
  if force and os.path.exists(LOCAL_FILENAME):
26
  try:
@@ -29,13 +30,19 @@ def download_dataset(force=False):
29
  pass
30
 
31
  if not os.path.exists(LOCAL_FILENAME):
32
- print(f"Downloading dataset from {DATASET_URL}...")
33
  try:
34
- # Try reading with pandas directly from URL
35
- # We use on_bad_lines='skip' to be robust
36
- df = pd.read_csv(DATASET_URL, on_bad_lines='skip')
37
- df.to_csv(LOCAL_FILENAME, index=False)
38
- print("Download complete.")
 
 
 
 
 
 
39
  except Exception as e:
40
  print(f"Error downloading dataset: {e}")
41
  pass
@@ -60,6 +67,7 @@ def read_csv_robust(filepath):
60
 
61
  for sep in separators:
62
  try:
 
63
  df = pd.read_csv(filepath, sep=sep, on_bad_lines='skip')
64
  # Heuristic: If we have > 1 columns, it's likely correct
65
  if len(df.columns) > 1:
@@ -126,7 +134,7 @@ def load_resources():
126
 
127
  def smart_translate(text, translator, nlp):
128
  """
129
- Translates text by chunking it into sentences to avoid truncation.
130
  Strictly preserves full content.
131
  """
132
  if not text or not isinstance(text, str) or text.strip() == "":
@@ -135,44 +143,59 @@ def smart_translate(text, translator, nlp):
135
  doc = nlp(text)
136
  sentences = [sent.text.strip() for sent in doc.sents if sent.text.strip()]
137
 
138
- chunks = []
139
- current_chunk = []
140
- current_len = 0
141
- MAX_LEN = 250
142
 
 
143
  for sent in sentences:
144
- sent_len = len(sent.split())
145
 
146
- if sent_len > MAX_LEN:
147
- if current_chunk:
148
- chunks.append(" ".join(current_chunk))
149
- current_chunk = []
150
- current_len = 0
151
- chunks.append(sent)
152
- continue
 
 
 
153
 
154
- if current_len + sent_len > MAX_LEN:
155
- chunks.append(" ".join(current_chunk))
156
- current_chunk = [sent]
157
- current_len = sent_len
 
 
 
 
 
 
 
 
 
 
 
158
  else:
159
- current_chunk.append(sent)
160
- current_len += sent_len
161
 
162
- if current_chunk:
163
- chunks.append(" ".join(current_chunk))
164
 
165
- translated_chunks = []
166
- for chunk in chunks:
 
167
  if not chunk.strip(): continue
168
  try:
 
 
169
  res = translator(chunk, max_length=512, truncation=True)
170
- translated_chunks.append(res[0]['translation_text'])
171
  except Exception as e:
172
  print(f"Chunk translation error: {e}")
173
- translated_chunks.append(chunk)
174
 
175
- return " ".join(translated_chunks)
176
 
177
  def process_rows(indices, token=None, progress=None):
178
  """
 
2
  import pandas as pd
3
  from transformers import pipeline
4
  import torch
5
+ from huggingface_hub import HfApi, hf_hub_download
6
  import spacy
7
  from spacy.lang.en import English
8
 
 
21
  def download_dataset(force=False):
22
  """
23
  Downloads the dataset if it doesn't exist locally or if forced.
24
+ Uses hf_hub_download to ensure raw file integrity (avoids parsing errors).
25
  """
26
  if force and os.path.exists(LOCAL_FILENAME):
27
  try:
 
30
  pass
31
 
32
  if not os.path.exists(LOCAL_FILENAME):
33
+ print(f"Downloading dataset from {ENV_REPO_ID}...")
34
  try:
35
+ # Use hf_hub_download to get the raw file
36
+ # local_dir="." downloads it to the current directory
37
+ downloaded_path = hf_hub_download(
38
+ repo_id=ENV_REPO_ID,
39
+ filename=DATA_FILE,
40
+ repo_type="dataset",
41
+ token=ENV_HF_TOKEN if ENV_HF_TOKEN else None,
42
+ local_dir=".",
43
+ local_dir_use_symlinks=False
44
+ )
45
+ print(f"Download complete: {downloaded_path}")
46
  except Exception as e:
47
  print(f"Error downloading dataset: {e}")
48
  pass
 
67
 
68
  for sep in separators:
69
  try:
70
+ # Try reading with specific separator
71
  df = pd.read_csv(filepath, sep=sep, on_bad_lines='skip')
72
  # Heuristic: If we have > 1 columns, it's likely correct
73
  if len(df.columns) > 1:
 
134
 
135
  def smart_translate(text, translator, nlp):
136
  """
137
+ Translates text by chunking it into sentences AND splitting long sentences to avoid truncation.
138
  Strictly preserves full content.
139
  """
140
  if not text or not isinstance(text, str) or text.strip() == "":
 
143
  doc = nlp(text)
144
  sentences = [sent.text.strip() for sent in doc.sents if sent.text.strip()]
145
 
146
+ final_chunks = []
 
 
 
147
 
148
+ # 1. Processing Sentences
149
  for sent in sentences:
150
+ words = sent.split()
151
 
152
+ # 2. Safety Check: If a single sentence is still huge (> 200 words)
153
+ # We split it by word count strictly
154
+ if len(words) > 200:
155
+ # Word-level chunking
156
+ chunk_size = 150 # Safe buffer
157
+ for i in range(0, len(words), chunk_size):
158
+ sub_chunk = " ".join(words[i:i+chunk_size])
159
+ final_chunks.append(sub_chunk)
160
+ else:
161
+ final_chunks.append(sent)
162
 
163
+ # 3. Grouping small chunks back together to optimize calls (optional but good)
164
+ # We can skip this if we want maximum safety, but grouping saves time.
165
+ # Let's group them again carefully.
166
+ grouped_chunks = []
167
+ current_group = []
168
+ current_len = 0
169
+ MAX_GROUP_LEN = 200 # Words
170
+
171
+ for chunk in final_chunks:
172
+ chunk_len = len(chunk.split())
173
+
174
+ if current_len + chunk_len > MAX_GROUP_LEN:
175
+ grouped_chunks.append(" ".join(current_group))
176
+ current_group = [chunk]
177
+ current_len = chunk_len
178
  else:
179
+ current_group.append(chunk)
180
+ current_len += chunk_len
181
 
182
+ if current_group:
183
+ grouped_chunks.append(" ".join(current_group))
184
 
185
+ # 4. Translation
186
+ translated_parts = []
187
+ for chunk in grouped_chunks:
188
  if not chunk.strip(): continue
189
  try:
190
+ # Truncation=True handles the edge case where even our safe chunk is slightly over token limit
191
+ # But since we split words at 200, it's very unlikely to hit 512 tokens.
192
  res = translator(chunk, max_length=512, truncation=True)
193
+ translated_parts.append(res[0]['translation_text'])
194
  except Exception as e:
195
  print(f"Chunk translation error: {e}")
196
+ translated_parts.append(chunk)
197
 
198
+ return " ".join(translated_parts)
199
 
200
  def process_rows(indices, token=None, progress=None):
201
  """