no_repeat_ngram_size added
Browse files5 unmodified lines6789101112103 unmodified lines11611711811811912012112212312413 unmodified lines13813914013814114214314414511 unmodified lines15715815915616016115816216316463 unmodified lines22822923022823123223366 unmodified lines300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348167 unmodified lines51651751847451952052152217 unmodified lines5405415424985435445455465476 unmodified lines5545555565115575585595605615625 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." "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) os.makedirs(os.path.dirname(name), exist_ok=True ) return name
def get_conv_vote_filename():11 unmodified lines except Exception as e: print(f"Failed to record vote: {e}")
# Yalın uzantı listeleri (sorunlu formatlar çıkarıldı)# Yalın uzantı listeleriIMAGE_EXTS = {"jpg", "jpeg", "png", "bmp", "gif", "tiff", "webp", "jfif"}# HEIC/HEIF: pillow-heif yoksa desteklemetry: import pillow_heif # noqa: F401 IMAGE_EXTS.update({"heic", "heif"})63 unmodified lines return load_image(image_input) if os.path.exists(image_input): return load_image(image_input) # muhtemelen base64 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 lines
return "\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 = 1 while 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] = content break i += 2
out_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 6 limited = deduped[:limit] if deduped else [] out_body = " ".join(limited) if limited else body out_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 lines prompt, chatbot.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt" ).unsqueeze(0).to(model_device)
# Stop kriteri (app.py uyumlu) # Stop kriteri stopping_criteria = _stop_criteria_from_conv(chatbot, input_ids)
# Deterministik üretim17 unmodified lines images=image_tensor, do_sample=False, # deterministik max_new_tokens=int(max_output_tokens), min_new_tokens=800, # en az bu kadar üret (step başlıkları garanti) min_new_tokens=350, # 800 -> 350 (tekrar riskini azalt) no_repeat_ngram_size=5, # tekrar bloklarını engelle repetition_penalty=float(repetition_penalty), use_cache=False, pad_token_id=eos_id,6 unmodified lines gen = outputs[0][input_ids.shape[1]:] response = chatbot.tokenizer.decode(gen, skip_special_tokens=True)
# ŞABLON ZORLAMA: Step1–9 + Structured # ŞABLON ZORLAMA + tekrar kırpma response = _enforce_section_template(response) response = _dedupe_and_clip_sections(response)
# Konuşmaya yerleştir if chatbot.conversation.messages and isinstance(chatbot.conversation.messages[-1], list):handler.py+55-8