bichnhan2701 commited on
Commit
0e732c5
·
1 Parent(s): de4b4f0

Update normalize logic

Browse files
app/services/enrichment/normalize.py CHANGED
@@ -55,8 +55,7 @@ Nhiệm vụ:
55
 
56
  YÊU CẦU ĐẦU RA:
57
  - Chỉ trả về văn bản đã chuẩn hóa
58
- - KHÔNG JSON, KHÔNG giải thích, KHÔNG markdown
59
- - KHÔNG thêm lời dẫn, giải thích, nhận xét hay meta-text.
60
 
61
  Văn bản đầu vào:
62
  \"\"\"{raw_text}\"\"\"
@@ -107,18 +106,42 @@ Văn bản đầu vào:
107
 
108
  try:
109
  raw = await loop.run_in_executor(None, call)
 
 
 
 
 
 
 
 
 
 
 
110
 
111
  if raw:
112
  text = raw.strip()
113
 
114
- # defensive cleanup (trường hợp model vẫn lỡ trả markdown)
115
  text = re.sub(r"^```.*?\n", "", text, flags=re.DOTALL)
116
  text = re.sub(r"```$", "", text)
 
 
 
 
 
 
 
 
 
117
  text = text.strip('"').strip("'").strip()
118
 
119
- if text:
120
  return text
121
 
 
 
 
 
122
  except GoogleAPIError as e:
123
  logging.error(f"[normalize_service] Gemini API error: {e}")
124
  except Exception as e:
@@ -129,7 +152,10 @@ Văn bản đầu vào:
129
  text = raw_text.strip()
130
  text = re.sub(r"\s+", " ", text)
131
 
132
- if text and text[-1] not in ".!?":
 
 
 
133
  text += "."
134
 
135
  def cap_sentences(s: str) -> str:
 
55
 
56
  YÊU CẦU ĐẦU RA:
57
  - Chỉ trả về văn bản đã chuẩn hóa
58
+ - KHÔNG JSON, KHÔNG giải thích, KHÔNG markdown, KHÔNG bọc trong ``` hoặc bất kỳ ký tự đặc biệt nào, chỉ trả về plain text thuần túy.
 
59
 
60
  Văn bản đầu vào:
61
  \"\"\"{raw_text}\"\"\"
 
106
 
107
  try:
108
  raw = await loop.run_in_executor(None, call)
109
+ def is_valid_normalized(text: str, raw: str) -> bool:
110
+ if not text:
111
+ return False
112
+ if len(text) < 50:
113
+ return False
114
+ if text.strip() in {".", "…"}:
115
+ return False
116
+ # không quá ngắn so với raw
117
+ if len(text) < 0.3 * len(raw):
118
+ return False
119
+ return True
120
 
121
  if raw:
122
  text = raw.strip()
123
 
124
+ # remove markdown
125
  text = re.sub(r"^```.*?\n", "", text, flags=re.DOTALL)
126
  text = re.sub(r"```$", "", text)
127
+
128
+ # remove meta-text Gemini
129
+ text = re.sub(
130
+ r"^the corrected text.*?is as follows:\s*",
131
+ "",
132
+ text,
133
+ flags=re.IGNORECASE | re.DOTALL,
134
+ )
135
+
136
  text = text.strip('"').strip("'").strip()
137
 
138
+ if is_valid_normalized(text, raw_text):
139
  return text
140
 
141
+ logging.warning(
142
+ "[normalize_service] Gemini returned invalid normalized text, falling back"
143
+ )
144
+
145
  except GoogleAPIError as e:
146
  logging.error(f"[normalize_service] Gemini API error: {e}")
147
  except Exception as e:
 
152
  text = raw_text.strip()
153
  text = re.sub(r"\s+", " ", text)
154
 
155
+ if not text or len(text) < 50:
156
+ return raw_text.strip()
157
+
158
+ if text[-1] not in ".!?":
159
  text += "."
160
 
161
  def cap_sentences(s: str) -> str: