Spaces:
Sleeping
Sleeping
Commit ·
a7fd3ba
1
Parent(s): 19d62ff
Enhance RAG conciseness and SFT aug
Browse filesFiles changed (3)
- utils/augment.py+16-1
- utils/rag.py+12-7
- vi/processing.py+34-2
1234588 unmodified lines949596979899100# augmentation utility agentimport reimport randomfrom typing import Dict, Tupleimport ftfy88 unmodified linesif ratio <= 0 or not text: return text, Falseif random.random() < ratio:bt = paraphraser.backtranslate(text, via_lang="vi")return bt if bt else text, bool(bt)return text, Falsedef consistency_ok(user: str, out: str, ratio: float, paraphraser) -> bool:12345688 unmodified lines9596979899100101102103104105106107108109110111112113114115# augmentation utility agentimport reimport difflibimport randomfrom typing import Dict, Tupleimport ftfy88 unmodified linesif ratio <= 0 or not text: return text, Falseif random.random() < ratio:bt = paraphraser.backtranslate(text, via_lang="vi")if not bt:return text, False# Guardrails: reject if too short/long or too dissimilar/similartry:orig_len = max(1, len(text))len_delta = abs(len(bt) - len(text)) / orig_lensim = difflib.SequenceMatcher(None, text, bt).ratio()# Accept if moderate change and not excessive driftif len_delta > 0.5:return text, Falseif sim < 0.45 or sim > 0.98:return text, Falseexcept Exception:passreturn bt, Truereturn text, Falsedef consistency_ok(user: str, out: str, ratio: float, paraphraser) -> bool:
43 unmodified lines444546474849504 unmodified lines5556575859606112 unmodified lines74757677787980818283847 unmodified lines92939495969798991001011021031041051061072 unmodified lines11011111211311411511643 unmodified linesself.nvidia_client = NvidiaClient(KeyRotator("NVIDIA_API"), nvidia_model)def clean_conversational_content(self, text: str) -> str:"""Remove conversational elements and non-medical information using NVIDIA model"""if not text or len(text.strip()) < 10:return text4 unmodified lines3. Keep only medically relevant information4. Preserve clinical facts, symptoms, diagnoses, treatments, and medical advice5. Maintain professional medical language6. Return only cleaned medical content, only plain text, no special characters, or formatting.Text to clean:{text}12 unmodified linesreturn textdef generate_context_from_qa(self, question: str, answer: str) -> str:"""Generate synthetic context from question and answer using NVIDIA model"""if not question or not answer:return ""prompt = f"""You are a medical knowledge expert. Given a medical question and its answer, generate a brief relevant medical context that would help someone understand the answer better. Write about 2 sentences that provide relevant background information. Use only plain text without any formatting or symbols.Question: {question}7 unmodified linestemperature=0.2,max_tokens=200)return context.strip() if context else ""except Exception as e:logger.warning(f"[RAG] Error generating context: {e}")return ""def convert_to_qca_format(self, instruction: str, user_input: str, output: str) -> Tuple[str, str, str]:"""Convert SFT format to QCA (Question, Context, Answer) format"""# Clean the content to remove conversational elementscleaned_input = self.clean_conversational_content(user_input)cleaned_output = self.clean_conversational_content(output)# Extract question from user inputquestion = self.extract_question(cleaned_input)2 unmodified linescontext = self.extract_context(cleaned_input, question, cleaned_output)# Clean answeranswer = cleaned_outputreturn question, context, answer43 unmodified lines444546474849504 unmodified lines5556575859606112 unmodified lines74757677787980818283847 unmodified lines92939495969798991001011021031041051061071081091101112 unmodified lines11411511611711811912012143 unmodified linesself.nvidia_client = NvidiaClient(KeyRotator("NVIDIA_API"), nvidia_model)def clean_conversational_content(self, text: str) -> str:"""Remove conversational elements and non-medical information using NVIDIA model; keep concise for embeddings."""if not text or len(text.strip()) < 10:return text4 unmodified lines3. Keep only medically relevant information4. Preserve clinical facts, symptoms, diagnoses, treatments, and medical advice5. Maintain professional medical language6. Return only cleaned medical content in 1-2 concise sentences suitable for dense retrieval embeddings. No lists, no headers.Text to clean:{text}12 unmodified linesreturn textdef generate_context_from_qa(self, question: str, answer: str) -> str:"""Generate synthetic, concise context (<=2 sentences) from question and answer, embedding-friendly."""if not question or not answer:return ""prompt = f"""You are a medical knowledge expert. Given a medical question and its answer, generate a brief relevant medical context that helps retrieval. Limit to 1–2 sentences, concise, avoid boilerplate, no enumerations.Question: {question}7 unmodified linestemperature=0.2,max_tokens=200)# Trim to a single short paragraphreturn (context or "").strip().split("\n")[0][:600]except Exception as e:logger.warning(f"[RAG] Error generating context: {e}")return ""def convert_to_qca_format(self, instruction: str, user_input: str, output: str) -> Tuple[str, str, str]:"""Convert SFT format to QCA (Question, Context, Answer) format, compressing for embedding suitability."""# Clean the content to remove conversational elementscleaned_input = self.clean_conversational_content(user_input)cleaned_output = self.clean_conversational_content(output)# Hard caps for embedding friendlinesscleaned_input = (cleaned_input or "")[:1200]cleaned_output = (cleaned_output or "")[:1200]# Extract question from user inputquestion = self.extract_question(cleaned_input)2 unmodified linescontext = self.extract_context(cleaned_input, question, cleaned_output)# Clean answer# Prefer short, direct answersanswer = cleaned_output[:800]return question, context, answer
6 unmodified lines78910111216 unmodified lines29303132333417 unmodified lines52535455565758596061626 unmodified lineslogger = logging.getLogger(__name__)def translate_sft_row(row: Dict[str, Any], translator, text_fields: List[str] = None) -> Dict[str, Any]:"""Translate specific text fields in an SFT row from English to Vietnamese.16 unmodified linestry:translated_row = translator.translate_dict(row, text_fields)logger.debug(f"Translated SFT row with fields: {text_fields}")return translated_rowexcept Exception as e:17 unmodified linesreturn rowif text_fields is None:# Default fields to translate in RAG formattext_fields = ["instruction", "input", "output"]try:translated_row = translator.translate_dict(row, text_fields)logger.debug(f"Translated RAG row with fields: {text_fields}")return translated_rowexcept Exception as e:6 unmodified lines78910111213141516171819202122232425262728293031323334353616 unmodified lines5354555657585960616217 unmodified lines8081828384858687888990919293946 unmodified lineslogger = logging.getLogger(__name__)def _vi_sanitize_text(s: str) -> str:"""Light Vietnamese sanitization for finetuning and RAG: strip extra spaces, limit repetition, preserve numbers/units."""if not isinstance(s, str):return st = s.strip()# Collapse repeated punctuation and whitespaceimport ret = re.sub(r"\s+", " ", t)t = re.sub(r"([.?!]){3,}", r"..", t)# Remove obvious repetition chunks (very heuristic)parts = t.split()if len(parts) > 20:window = 6seen = set()filtered = []for i in range(len(parts)):ngram = " ".join(parts[max(0, i-window):i+1])if ngram in seen:continueseen.add(ngram)filtered.append(parts[i])t = " ".join(filtered)return tdef translate_sft_row(row: Dict[str, Any], translator, text_fields: List[str] = None) -> Dict[str, Any]:"""Translate specific text fields in an SFT row from English to Vietnamese.16 unmodified linestry:translated_row = translator.translate_dict(row, text_fields)# Sanitize translated fieldsfor f in text_fields:if f in translated_row.get("sft", {}):translated_row["sft"][f] = _vi_sanitize_text(translated_row["sft"][f])logger.debug(f"Translated SFT row with fields: {text_fields}")return translated_rowexcept Exception as e:17 unmodified linesreturn rowif text_fields is None:# Default fields to translate in RAG format (Q, A, C)text_fields = ["question", "answer", "context"]try:translated_row = translator.translate_dict(row, text_fields)# Sanitize translated fieldsfor f in text_fields:if f in translated_row:translated_row[f] = _vi_sanitize_text(translated_row[f])logger.debug(f"Translated RAG row with fields: {text_fields}")return translated_rowexcept Exception as e:
utils/augment.py+16-1
utils/rag.py+12-7
vi/processing.py+34-2