Spaces:
Sleeping
Sleeping
Commit ·
36d9d96
1
Parent(s): 20c0231
Add inference fallback for embedding errors
Browse filesFiles changed (2)
- app.py+2-1
- src/inference.py+77-4
452 unmodified lines453454455456457458459452 unmodified linesfor name in ["Negative", "Neutral", "Positive"]:val = _safe_float(probs.get(name))bars.append(f'<div class="prob-row"><span>{name}</span><div class="bar"><i style="width:{val * 100:.1f}%"></i></div><b>{val:.2f}</b></div>')return f'<div class="overall-card"><div class="small-label">Overall sentiment</div><div class="overall-main">{_chip(label)} <span class="conf">confidence {conf:.2f}</span></div>{"".join(bars)}</div>'def _join_aspects(items: List[str]) -> str:452 unmodified lines453454455456457458459460452 unmodified linesfor name in ["Negative", "Neutral", "Positive"]:val = _safe_float(probs.get(name))bars.append(f'<div class="prob-row"><span>{name}</span><div class="bar"><i style="width:{val * 100:.1f}%"></i></div><b>{val:.2f}</b></div>')fallback = '<div class="small-label">Fallback inference mode used for this sample.</div>' if result.get("fallback") else ""return f'<div class="overall-card"><div class="small-label">Overall sentiment</div><div class="overall-main">{_chip(label)} <span class="conf">confidence {conf:.2f}</span></div>{"".join(bars)}{fallback}</div>'def _join_aspects(items: List[str]) -> str:
70 unmodified lines71727374757682 unmodified lines15916016116216316459 unmodified lines22422522622722822923023139 unmodified lines27127227327427527627727870 unmodified lines"bad", "poor", "cheap", "terrible", "awful", "small", "large", "tight", "loose", "thin","worth", "disappointed", "return", "returned", "recommend", "flattering", "beautiful",}_STOPWORDS = {"a", "an", "the", "and", "or", "but", "if", "then", "than", "so", "as", "at", "by", "for", "from","in", "into", "of", "on", "to", "with", "without", "is", "are", "was", "were", "be", "been", "being",82 unmodified linesreturn resultdef _slice_model_out(out: Dict, start: int, end: int) -> Dict:sliced = {}for k, v in out.items():59 unmodified linesmeta_df = _meta_dict_to_df(product_meta)meta_vec = torch.from_numpy(self.meta_encoder.transform(meta_df)).float().to(self.device)with torch.no_grad():out = self.model(input_ids, attn_mask, meta_vec)preds = out["logits"][0].argmax(dim=-1).cpu().numpy()result = {39 unmodified lines)meta_vec = torch.from_numpy(self.meta_encoder.transform(meta_df)).float().to(self.device)with torch.no_grad():out = self.model(input_ids, attn_mask, meta_vec)preds = out["logits"].argmax(dim=-1).cpu().numpy()for j in range(len(chunk)):70 unmodified lines717273747576777882 unmodified lines16116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422559 unmodified lines28528628728828929029129229329429539 unmodified lines33533633733833934034134234334434534634734834935035170 unmodified lines"bad", "poor", "cheap", "terrible", "awful", "small", "large", "tight", "loose", "thin","worth", "disappointed", "return", "returned", "recommend", "flattering", "beautiful",}_POSITIVE_HINTS = {"good", "great", "love", "loved", "perfect", "nice", "excellent", "comfortable", "soft", "worth", "recommend", "flattering", "beautiful"}_NEGATIVE_HINTS = {"bad", "poor", "cheap", "terrible", "awful", "small", "large", "tight", "loose", "thin", "disappointed", "return", "returned", "broke", "torn"}_STOPWORDS = {"a", "an", "the", "and", "or", "but", "if", "then", "than", "so", "as", "at", "by", "for", "from","in", "into", "of", "on", "to", "with", "without", "is", "are", "was", "were", "be", "been", "being",82 unmodified linesreturn resultdef _fallback_prediction(review_text: str, product_meta: Dict, reason: str = "") -> Dict:evidence = _text_evidence_by_aspect(review_text)aspect_details = {}aspect_labels = {}pos_total = 0neg_total = 0for aspect in cfg.ASPECTS:terms = evidence.get(aspect, [])pos_hits = [t for t in terms if t in _POSITIVE_HINTS]neg_hits = [t for t in terms if t in _NEGATIVE_HINTS]if neg_hits and len(neg_hits) >= len(pos_hits):label = "Negative"confidence = 0.62neg_total += 1elif pos_hits:label = "Positive"confidence = 0.62pos_total += 1elif terms:label = "Not_Mentioned"confidence = 0.55else:label = "Not_Mentioned"confidence = 0.60aspect_labels[aspect] = labelaspect_details[aspect] = {"label": label,"confidence": confidence,"class_probs": {"Not_Mentioned": 0.70 if label == "Not_Mentioned" else 0.20,"Positive": confidence if label == "Positive" else 0.20,"Negative": confidence if label == "Negative" else 0.20,},}overall_label = "Negative" if neg_total > pos_total else "Positive" if pos_total > 0 else "Neutral"return {"aspects": aspect_labels,"aspect_details": aspect_details,"overall": {"label": overall_label,"confidence": 0.60,"class_probs": {"Negative": 0.60 if overall_label == "Negative" else 0.20,"Neutral": 0.60 if overall_label == "Neutral" else 0.20,"Positive": 0.60 if overall_label == "Positive" else 0.20},},"metadata_summary": _meta_summary(product_meta),"meta_attention_by_aspect": {aspect: {"features": 0.50, "categories": 0.25, "numeric": 0.25}for aspect in cfg.ASPECTS},"top_meta_source_by_aspect": {aspect: {"source": "features", "weight": 0.50}for aspect in cfg.ASPECTS},"fallback": True,"fallback_reason": reason or "Model embedding index guard activated.",}def _slice_model_out(out: Dict, start: int, end: int) -> Dict:sliced = {}for k, v in out.items():59 unmodified linesmeta_df = _meta_dict_to_df(product_meta)meta_vec = torch.from_numpy(self.meta_encoder.transform(meta_df)).float().to(self.device)try:with torch.no_grad():out = self.model(input_ids, attn_mask, meta_vec)except IndexError as exc:return _fallback_prediction(review_text, product_meta, str(exc))preds = out["logits"][0].argmax(dim=-1).cpu().numpy()result = {39 unmodified lines)meta_vec = torch.from_numpy(self.meta_encoder.transform(meta_df)).float().to(self.device)try:with torch.no_grad():out = self.model(input_ids, attn_mask, meta_vec)except IndexError as exc:for item in chunk:results.append(_fallback_prediction(item.get("review_text", ""),item.get("product_meta", {}),str(exc),))continuepreds = out["logits"].argmax(dim=-1).cpu().numpy()for j in range(len(chunk)):
app.py+2-1
src/inference.py+77-4