Spaces:
Sleeping
Sleeping
Commit ·
19d62ff
1
Parent(s): 050b5e3
Upd RAG schema to QAC format
Browse filesFiles changed (5)
- app.py+11-10
- utils/augment.py+1-1
- utils/llm.py+3-3
- utils/rag.py+17-37
- utils/schema.py+54-1
15 unmodified lines1617181920212248 unmodified lines717273747576777879808182838493 unmodified lines178179180181182183184185186187188189190191192189 unmodified lines38238338438538638738815 unmodified linesfrom utils.rag import process_file_into_ragfrom utils.drive_saver import DriveSaverfrom utils.llm import Paraphraserfrom utils.schema import CentralisedWriterfrom utils.token import get_credentials, exchange_code, build_auth_urlfrom vi.translator import VietnameseTranslator48 unmodified linesclass AugmentOptions(BaseModel):# ratios are 0..1paraphrase_ratio: float = 0.0paraphrase_outputs: bool = Falsebacktranslate_ratio: float = 0.0style_standardize: bool = Truedeidentify: bool = Truededupe: bool = Truemax_chars: int = 5000 # cap extremely long contextsconsistency_check_ratio: float = 0.0 # small ratio e.g. 0.01# KD / distillation (optional, keeps default off)distill_fraction: float = 0.0 # for unlabeled onlyexpand: bool = True # Enable back-translation and complex augmentation93 unmodified linesheaders: {{ "Content-Type": "application/json" }},body: JSON.stringify({{augment: {{paraphrase_ratio: 0.1,backtranslate_ratio: 0.00, // Increase to 0.05-0.1 for back-translationparaphrase_outputs: false,style_standardize: true,deidentify: true,dedupe: true,max_chars: 5000,expand: true,max_aug_per_sample: 2}},sample_limit: null, // Sample down (currently disabled)seed: 42,189 unmodified linesset_state(message="processing", progress=0.05)# Writerwriter = CentralisedWriter(jsonl_path=jsonl_path, csv_path=csv_path)# Load translator if Vietnamese translation is requestedtranslator = None15 unmodified lines1617181920212248 unmodified lines717273747576777879808182838493 unmodified lines178179180181182183184185186187188189190191192193189 unmodified lines38338438538638738838915 unmodified linesfrom utils.rag import process_file_into_ragfrom utils.drive_saver import DriveSaverfrom utils.llm import Paraphraserfrom utils.schema import CentralisedWriter, RAGWriterfrom utils.token import get_credentials, exchange_code, build_auth_urlfrom vi.translator import VietnameseTranslator48 unmodified linesclass AugmentOptions(BaseModel):# ratios are 0..1paraphrase_ratio: float = 0.2paraphrase_outputs: bool = Truebacktranslate_ratio: float = 0.1style_standardize: bool = Truedeidentify: bool = Truededupe: bool = Truemax_chars: int = 5000 # cap extremely long contextsconsistency_check_ratio: float = 0.05 # small ratio e.g. 0.01# KD / distillation (optional, keeps default off)distill_fraction: float = 0.0 # for unlabeled onlyexpand: bool = True # Enable back-translation and complex augmentation93 unmodified linesheaders: {{ "Content-Type": "application/json" }},body: JSON.stringify({{augment: {{paraphrase_ratio: 0.2,backtranslate_ratio: 0.1,paraphrase_outputs: true,style_standardize: true,deidentify: true,dedupe: true,max_chars: 5000,expand: true,max_aug_per_sample: 2,consistency_check_ratio: 0.05}},sample_limit: null, // Sample down (currently disabled)seed: 42,189 unmodified linesset_state(message="processing", progress=0.05)# Writerwriter = RAGWriter(jsonl_path=jsonl_path, csv_path=csv_path) if params.rag_processing else CentralisedWriter(jsonl_path=jsonl_path, csv_path=csv_path)# Load translator if Vietnamese translation is requestedtranslator = None
92 unmodified lines9394959697989992 unmodified linesdef maybe_backtranslate(text: str, ratio: float, paraphraser) -> Tuple[str, bool]:if ratio <= 0 or not text: return text, Falseif random.random() < ratio:bt = paraphraser.backtranslate(text, via_lang="de")return bt if bt else text, bool(bt)return text, False92 unmodified lines9394959697989992 unmodified linesdef maybe_backtranslate(text: str, ratio: float, paraphraser) -> Tuple[str, bool]:if 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, False
153 unmodified lines154155156157158159160161162163164165166167168169170171153 unmodified linesreturn self._clean_resp(out) if out else text# ————— Translate & Backtranslate —————def translate(self, text: str, target_lang: str = "de") -> Optional[str]:if not text: return textprompt = f"Translate to {target_lang}. Keep meaning exact, preserve medical terms:\n\n{text}"out = self.nv.generate(prompt, temperature=0.0, max_tokens=min(800, len(text)+100))if out: return out.strip()return self.gm_easy.generate(prompt, max_output_tokens=min(800, len(text)+100))def backtranslate(self, text: str, via_lang: str = "de") -> Optional[str]:if not text: return textmid = self.translate(text, target_lang=via_lang)if not mid: return Noneprompt = f"Translate the following {via_lang} text back to English, preserving the exact meaning:\n\n{mid}"out = self.nv.generate(prompt, temperature=0.0, max_tokens=min(900, len(text)+150))if out: return out.strip()res = self.gm_easy.generate(prompt, max_output_tokens=min(900, len(text)+150))153 unmodified lines154155156157158159160161162163164165166167168169170171153 unmodified linesreturn self._clean_resp(out) if out else text# ————— Translate & Backtranslate —————def translate(self, text: str, target_lang: str = "vi") -> Optional[str]:if not text: return textprompt = f"Translate to {target_lang}. Keep meaning exact, preserve medical terms:\n\n{text}"out = self.nv.generate(prompt, temperature=0.0, max_tokens=min(800, len(text)+100))if out: return out.strip()return self.gm_easy.generate(prompt, max_output_tokens=min(800, len(text)+100))def backtranslate(self, text: str, via_lang: str = "vi") -> Optional[str]:if not text: return textmid = self.translate(text, target_lang=via_lang)if not mid: return Noneprompt = f"Translate the following Vietnamese text back to English, preserving the exact meaning:\n\n{mid}"out = self.nv.generate(prompt, temperature=0.0, max_tokens=min(900, len(text)+150))if out: return out.strip()res = self.gm_easy.generate(prompt, max_output_tokens=min(900, len(text)+150))
4 unmodified lines5678910111213174 unmodified lines18818919019119219319419519619719819920020120220320420550 unmodified lines25625725825926026126226326426526626726826927027114 unmodified lines2862872882892902912922932942952962972982993003013023033043053063073083093103113123133143154 unmodified linesimport randomfrom typing import Dict, List, Tuple, Optional, Callablefrom utils.schema import sft_rowfrom utils.llm import NvidiaClient, KeyRotatorfrom vi.processing import translate_rag_row, should_translate, log_translation_stats# Loggerlogger = logging.getLogger("rag_processor")174 unmodified linesif not question or not answer:continue# Create RAG-specific instructionrag_instruction = "Answer the medical question based on the provided context. If the context is insufficient, provide the best available medical information."# Format user input as QCAif context:rag_user = f"Question: {question}\n\nContext: {context}"else:rag_user = f"Question: {question}"# Commit the RAG-formatted rowif self._commit_rag_row(writer, source, rid, "rag_medical_qa",rag_instruction, rag_user, answer,stats, dedupe_seen=dedupe_seen, translator=translator, opts=opts):written += 150 unmodified linescontext = self.generate_context_from_qa(question, answer)rid = str(k)rag_instruction = "Answer the biomedical question based on the provided context."if context:rag_user = f"Question: {question}\n\nContext: {context}"else:rag_user = f"Question: {question}"# Commit the RAG-formatted rowif self._commit_rag_row(writer, source, rid, "rag_biomedical_qa",rag_instruction, rag_user, answer,stats, dedupe_seen=dedupe_seen, translator=translator, opts=opts):written += 114 unmodified lineslogger.info(f"[RAG] {source} RAG processing done count={count} written={written}")return countdef _commit_rag_row(self, writer, source: str, rid: str, task: str,instruction: str, user_input: str, output: str,stats: Dict, dedupe_seen: set = None, translator=None, opts=None) -> bool:"""Commit a RAG-formatted row to the writer"""# Simple deduplication based on content hashif dedupe_seen is not None:content_hash = hashlib.md5(f"{user_input}{output}".encode()).hexdigest()if content_hash in dedupe_seen:stats["dedup_skipped"] = stats.get("dedup_skipped", 0) + 1return Falsededupe_seen.add(content_hash)meta = {"rag_processing": True, "format": "qca"}row = sft_row(instruction, user_input, output, source=source, rid=rid, task=task, meta=meta)# Apply Vietnamese translation if requestedif should_translate(opts.get("vietnamese_translation", False) if opts else False, translator):try:row = translate_rag_row(row, translator)meta["vietnamese_translated"] = Truerow["meta"] = metaexcept Exception as e:logger.error(f"Failed to translate RAG row: {e}")writer.write(row)stats["written"] = stats.get("written", 0) + 1return True4 unmodified lines5678910111213174 unmodified lines18818919019119219319419550 unmodified lines24624724824925025125225314 unmodified lines2682692702712722732742752762772782792802812822832842852862872882892902912922932942954 unmodified linesimport randomfrom typing import Dict, List, Tuple, Optional, Callablefrom utils.schema import sft_row, rag_rowfrom utils.llm import NvidiaClient, KeyRotatorfrom vi.processing import should_translate# Loggerlogger = logging.getLogger("rag_processor")174 unmodified linesif not question or not answer:continue# Commit the RAG-formatted row (QAC)if self._commit_rag_row(writer, rid, question, context, answer,stats, dedupe_seen=dedupe_seen, translator=translator, opts=opts):written += 150 unmodified linescontext = self.generate_context_from_qa(question, answer)rid = str(k)# Commit the RAG-formatted row (QAC)if self._commit_rag_row(writer, rid, question, context, answer,stats, dedupe_seen=dedupe_seen, translator=translator, opts=opts):written += 114 unmodified lineslogger.info(f"[RAG] {source} RAG processing done count={count} written={written}")return countdef _commit_rag_row(self, writer, rid: str, question: str, context: str, answer: str,stats: Dict, dedupe_seen: set = None, translator=None, opts=None) -> bool:"""Commit a RAG-formatted row (QAC) to the writer"""# Simple deduplication based on content hashif dedupe_seen is not None:content_hash = hashlib.md5(f"{question}{context}{answer}".encode()).hexdigest()if content_hash in dedupe_seen:stats["dedup_skipped"] = stats.get("dedup_skipped", 0) + 1return Falsededupe_seen.add(content_hash)row = rag_row(question=question, context=context, answer=answer, rid=rid)# Apply Vietnamese translation if requested (translate Q/A/C fields directly)if should_translate(opts.get("vietnamese_translation", False) if opts else False, translator):try:if translator:row = translator.translate_dict(row, ["question", "answer", "context"])row["vi_translated"] = Trueexcept Exception as e:logger.error(f"Failed to translate RAG row: {e}")writer.write(row)stats["written"] = stats.get("written", 0) + 1return True
123461 unmodified lines666768# Centralized SFT writer (JSONL + CSV)import csvimport orjsonfrom typing import Optional, Dict61 unmodified linesself.jsonl_fp.close()finally:self.csv_fp.close()123461 unmodified lines66676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121# Centralized SFT writer (JSONL + CSV) and RAG writerimport csvimport orjsonfrom typing import Optional, Dict61 unmodified linesself.jsonl_fp.close()finally:self.csv_fp.close()# —— RAG (QAC) schema ——def rag_row(question: str, context: str, answer: str, rid: str):return {"id": rid,"question": question or "","answer": answer or "","context": context or ""}def is_valid_rag_row(row: Dict, max_chars: int = 20000) -> bool:q = row.get("question", "")a = row.get("answer", "")c = row.get("context", "")if not (q and a):return Falseif any(len(x) > max_chars for x in (q, a, c)):return Falsereturn Trueclass RAGWriter:"""Streams JSONL + CSV for RAG (QAC) format with columns: id, question, answer, context."""def __init__(self, jsonl_path: str, csv_path: str):self.jsonl_fp = open(jsonl_path, "wb")self.csv_fp = open(csv_path, "w", newline="", encoding="utf-8")self.csv_wr = csv.DictWriter(self.csv_fp, fieldnames=["id","question","answer","context"])self.csv_wr.writeheader()def write(self, row: dict):if not is_valid_rag_row(row):logger.warning(f"[RAG-WRITER] Skipping invalid row id={row.get('id')} "f"(len q={len(row.get('question',''))}, a={len(row.get('answer',''))}, c={len(row.get('context',''))})")returnself.jsonl_fp.write(orjson.dumps(row))self.jsonl_fp.write(b"\n")self.csv_wr.writerow({"id": row.get("id",""),"question": row.get("question",""),"answer": row.get("answer",""),"context": row.get("context","")})def close(self):try:self.jsonl_fp.close()finally:self.csv_fp.close()
app.py+11-10
utils/augment.py+1-1
utils/llm.py+3-3
utils/rag.py+17-37
utils/schema.py+54-1