no_repeat_ngram_size added
Browse files5 unmodified lines67891011103 unmodified lines11511611711811912012113 unmodified lines13513613713813914014111 unmodified lines15315415515615715815916016163 unmodified lines22522622722822923023166 unmodified lines298299300301302303167 unmodified lines47147247347447547647717 unmodified lines4954964974984995005016 unmodified lines5085095105115125135145155 unmodified lines- Model dtype/device ile uyumlu görüntü tensörü (3D/4D/5D destekli)- Sağlam URL/base64 işleme, güvenli logging, opsiyonel HF upload- Zorunlu başlık şablonu + min_new_tokens ile tam Step 1–9 çıktısı"""import os103 unmodified lines"Step 8: T Wave Analysis\n""Step 9: QT/QTc Interval Analysis\n""Structured Clinical Impression:\n""If a section is normal, write 'Normal' and give a brief justification.")# ---------- Yardımcılar ----------13 unmodified linesdef get_conv_log_filename():t = datetime.datetime.now()name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-user_conv.json")os.makedirs(os.path.dirname(name), exist_ok=True)return namedef get_conv_vote_filename():11 unmodified linesexcept Exception as e:print(f"Failed to record vote: {e}")# Yalın uzantı listeleri (sorunlu formatlar çıkarıldı)IMAGE_EXTS = {"jpg", "jpeg", "png", "bmp", "gif", "tiff", "webp", "jfif"}# HEIC/HEIF: pillow-heif yoksa desteklemetry:import pillow_heif # noqa: F401IMAGE_EXTS.update({"heic", "heif"})63 unmodified linesreturn load_image(image_input)if os.path.exists(image_input):return load_image(image_input)# muhtemelen base64return process_base64_image(image_input)if isinstance(image_input, dict) and "image" in image_input:return process_base64_image(image_input["image"])66 unmodified linesreturn "\n\n".join(filled)# ---------- Oturum / Konuşma ----------class InferenceDemo(object):167 unmodified linesprompt, chatbot.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(model_device)# Stop kriteri (app.py uyumlu)stopping_criteria = _stop_criteria_from_conv(chatbot, input_ids)# Deterministik üretim17 unmodified linesimages=image_tensor,do_sample=False, # deterministikmax_new_tokens=int(max_output_tokens),min_new_tokens=800, # en az bu kadar üret (step başlıkları garanti)repetition_penalty=float(repetition_penalty),use_cache=False,pad_token_id=eos_id,6 unmodified linesgen = outputs[0][input_ids.shape[1]:]response = chatbot.tokenizer.decode(gen, skip_special_tokens=True)# ŞABLON ZORLAMA: Step1–9 + Structuredresponse = _enforce_section_template(response)# Konuşmaya yerleştirif chatbot.conversation.messages and isinstance(chatbot.conversation.messages[-1], list):5 unmodified lines6789101112103 unmodified lines11611711811912012112212312413 unmodified lines13813914014114214314414511 unmodified lines15715815916016116216316463 unmodified lines22822923023123223366 unmodified lines300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348167 unmodified lines51651751851952052152217 unmodified lines5405415425435445455465476 unmodified lines5545555565575585595605615625 unmodified lines- Model dtype/device ile uyumlu görüntü tensörü (3D/4D/5D destekli)- Sağlam URL/base64 işleme, güvenli logging, opsiyonel HF upload- Zorunlu başlık şablonu + min_new_tokens ile tam Step 1–9 çıktısı- Tekrarları engelleme (no_repeat_ngram_size) + post-format dedup"""import os103 unmodified lines"Step 8: T Wave Analysis\n""Step 9: QT/QTc Interval Analysis\n""Structured Clinical Impression:\n""If a section is normal, write 'Normal' and give a brief justification. ""Each section must be 1–3 concise sentences. Do not repeat identical statements. ""Write the final diagnostic impression only once in 'Structured Clinical Impression' and do not restate it elsewhere.")# ---------- Yardımcılar ----------13 unmodified linesdef get_conv_log_filename():t = datetime.datetime.now()name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-user_conv.json")os.makedirs(os.path.dirname(name), exist_ok=True)return namedef get_conv_vote_filename():11 unmodified linesexcept Exception as e:print(f"Failed to record vote: {e}")# Yalın uzantı listeleriIMAGE_EXTS = {"jpg", "jpeg", "png", "bmp", "gif", "tiff", "webp", "jfif"}try:import pillow_heif # noqa: F401IMAGE_EXTS.update({"heic", "heif"})63 unmodified linesreturn load_image(image_input)if os.path.exists(image_input):return load_image(image_input)return process_base64_image(image_input)if isinstance(image_input, dict) and "image" in image_input:return process_base64_image(image_input["image"])66 unmodified linesreturn "\n\n".join(filled)def _sent_split(s: str):return [x.strip() for x in re.split(r'(?<=[.!?])\s+', s.strip()) if x.strip()]def _norm_key(s: str):return re.sub(r'\W+', ' ', s.lower()).strip()def _dedupe_and_clip_sections(text: str) -> str:"""Şablon oluşmuş metni alır, her bölümde tekrar eden cümleleri siler,uzunluğu kısaltır (Steps: ≤3 cümle, Impression: ≤6 cümle) ve birleştirir."""pieces = _SECTION_RE.split(text)found = {}i = 1while i + 1 < len(pieces):heading = pieces[i].strip()content = pieces[i + 1].strip()for canonical in SECTION_ORDER:if heading.lower().startswith(canonical.lower().rstrip(":")):found[canonical] = contentbreaki += 2out_sections = []for sec in SECTION_ORDER:body = (found.get(sec, "") or "").strip()sents = _sent_split(body)seen = set()deduped = []for s in sents:k = _norm_key(s)if k not in seen:seen.add(k)deduped.append(s)limit = 3 if sec.startswith("Step") else 6limited = deduped[:limit] if deduped else []out_body = " ".join(limited) if limited else bodyout_sections.append(f"{sec}\n{out_body}" if out_body else f"{sec}\n")return "\n\n".join(out_sections)# ---------- Oturum / Konuşma ----------class InferenceDemo(object):167 unmodified linesprompt, chatbot.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).to(model_device)# Stop kriteristopping_criteria = _stop_criteria_from_conv(chatbot, input_ids)# Deterministik üretim17 unmodified linesimages=image_tensor,do_sample=False, # deterministikmax_new_tokens=int(max_output_tokens),min_new_tokens=350, # 800 -> 350 (tekrar riskini azalt)no_repeat_ngram_size=5, # tekrar bloklarını engellerepetition_penalty=float(repetition_penalty),use_cache=False,pad_token_id=eos_id,6 unmodified linesgen = outputs[0][input_ids.shape[1]:]response = chatbot.tokenizer.decode(gen, skip_special_tokens=True)# ŞABLON ZORLAMA + tekrar kırpmaresponse = _enforce_section_template(response)response = _dedupe_and_clip_sections(response)# Konuşmaya yerleştirif chatbot.conversation.messages and isinstance(chatbot.conversation.messages[-1], list):
handler.py+55-8