Spaces:
No application file
No application file
Upload 3 files
Browse filesFiles changed (3)
12345678910111213141516171819202122232425262728# Contextual Adaptivity Evaluator — Final Version (Gradio Space)This Space computes a Contextual Adaptivity score for candidate text given a context & reference. It combines:- BLEU-like n-gram overlap (with brevity penalty)- Sentiment alignment (via HF Inference API)- Contextual alignment (embeddings + lexical overlap)- Terminology extraction & consistency score- Combined adaptivity score (weighted)## Deployment instructions1. Create a new Space on https://huggingface.co/new-space (choose SDK: Gradio, hardware: CPU Basic is fine)2. Upload these files: `app.py`, `requirements.txt`, `README.md`3. In your Space → Settings → Secrets add:- Name: `HF_API_TOKEN`- Value: your HF token (read permission)4. Save and wait for the Space to build. On success the Gradio app will appear.5. Use the "Single Eval" tab for one-off checks; use the "Batch CSV / Table" tab for bulk processing and CSV export.## CSV format expectedThe CSV should include columns (headers recommended): `reference`,`candidate`,`context`.If headers are missing, the reader will attempt to fill missing cols with empty strings.## Notes- The Space calls Hugging Face Inference API for embeddings & sentiment; API token is required.- This implementation caches embeddings/sentiment results while the process runs (LRU cache).- For high-volume production use, consider batching, rate-limiting, or using your own inference endpoints.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304# force rebuildimport osimport mathimport requestsimport numpy as npimport gradio as grimport pandas as pdfrom io import BytesIO, StringIOfrom collections import Counterimport refrom functools import lru_cache# -----------------------------# Configuration# -----------------------------HF_API_TOKEN = os.getenv("HF_API_TOKEN") # must be added to Space SecretsEMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"SENT_MODEL = "distilbert-base-uncased-finetuned-sst-2-english"API_URL_EMBED = f"https://api-inference.huggingface.co/models/{EMBED_MODEL}"API_URL_SENT = f"https://api-inference.huggingface.co/models/{SENT_MODEL}"HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"} if HF_API_TOKEN else {}# -----------------------------# Helpers: HF requests with basic retry# -----------------------------def hf_request(url, payload, timeout=30):try:r = requests.post(url, headers=HEADERS, json=payload, timeout=timeout)r.raise_for_status()return r.json()except Exception as e:# Return None on any failure (caller should handle)print(f"[hf_request] request to {url} failed: {e}")return None# -----------------------------# Caching: use simple LRU caches for embeddings and sentiment to reduce API calls on repeated inputs.# Note: LRU cache persists during process lifetime only.# -----------------------------@lru_cache(maxsize=1024)def get_embedding_cached(text):if not text or not str(text).strip():return tuple([0.0]*384)data = hf_request(API_URL_EMBED, {"inputs": text})if not data or not isinstance(data, list):return tuple([0.0]*384)vec = data[0]try:vec = [float(x) for x in vec]except Exception:vec = list(vec)return tuple(vec)@lru_cache(maxsize=2048)def sentiment_cached(text):if not text or not str(text).strip():return 0.0data = hf_request(API_URL_SENT, {"inputs": text})if not data:return 0.0entry = data[0]if isinstance(entry, list) and len(entry)>0:label = entry[0].get("label","")score = entry[0].get("score",0.0)elif isinstance(entry, dict):label = entry.get("label","")score = entry.get("score",0.0)else:return 0.0return float(score) if str(label).upper().startswith("POS") else -float(score)# -----------------------------# Text utils# -----------------------------_STOPWORDS = set(["the","and","is","in","to","of","a","for","on","with","that","this","it","as","are","was","be","by","an","or","from","at","which"])def tokenize(text):if not text:return []text = re.sub(r"[^\w\s]", " ", str(text).lower())toks = [t for t in text.split() if t and t not in _STOPWORDS]return toksdef ngrams(tokens, n):return [" ".join(tokens[i:i+n]) for i in range(len(tokens)-n+1)] if len(tokens) >= n else []def bleu_like(reference, candidate, N=4):r = tokenize(reference)c = tokenize(candidate)if not c:return 0.0precisions = []for n in range(1, N+1):rn = ngrams(r,n)cn = ngrams(c,n)if not cn:precisions.append(0.0); continuerc = Counter(rn)match = 0for g in cn:if rc.get(g,0) > 0:match += 1rc[g] -= 1precisions.append(match/len(cn))smooth = 1e-9log_sum = sum(math.log(p + smooth) for p in precisions)geo = math.exp(log_sum / len(precisions))bp = 1.0if len(c) < len(r):bp = math.exp(1 - len(r)/len(c)) if len(c)>0 else 0.0return float(geo * bp)# -----------------------------# Terminology extraction & consistency# -----------------------------def extract_terms(text, min_len=4, top_k=40):toks = tokenize(text)cands = []for n in (3,2):cands += ngrams(toks, n)cands += [t for t in toks if len(t) >= min_len]counts = Counter(cands)most = [t for t,_ in counts.most_common(top_k)]filtered = [t for t in most if len(t) >= min_len]return filtered[:top_k]def terminology_consistency(reference, candidate):terms = extract_terms(reference)cand_toks = set(tokenize(candidate))present = [t for t in terms if all(tok in cand_toks for tok in t.split())]missing = [t for t in terms if t not in present]score = (len(present) / max(1, len(terms))) if terms else 1.0return {"terms": terms, "present": present, "missing": missing, "score": score}# -----------------------------# Context alignment (lexical + semantic + contradiction penalty)# -----------------------------def cosine_similarity(a,b):a = np.array(a, dtype=float)b = np.array(b, dtype=float)if np.linalg.norm(a)==0 or np.linalg.norm(b)==0:return 0.0return float(np.dot(a,b)/(np.linalg.norm(a)*np.linalg.norm(b)))def semantic_similarity(a,b):a_emb = get_embedding_cached(a)b_emb = get_embedding_cached(b)sim = cosine_similarity(a_emb, b_emb)return (sim + 1) / 2def context_alignment(context, candidate):ctx_tokens = tokenize(context)cand_tokens = tokenize(candidate)lex_overlap = 0.0if ctx_tokens and cand_tokens:ctx_set = set(ctx_tokens)lex_overlap = sum(1 for t in cand_tokens if t in ctx_set) / len(cand_tokens)sem_sim = semantic_similarity(context, candidate) if context and context.strip() else 0.0contra = any(w in str(candidate).lower() for w in ["not","no","never","don't","doesn't"])contra_penalty = 0.4 if contra else 0.0score = max(0.0, 0.6*sem_sim + 0.4*lex_overlap - contra_penalty)return float(score)# -----------------------------# Combined adaptivity computation for a single row# -----------------------------def compute_row(reference, candidate, context, N, weights):bleu = bleu_like(reference or "", candidate or "", N)sent_ref = sentiment_cached(reference or "")sent_cand = sentiment_cached(candidate or "")sent_align = 1 - min(1, abs(sent_ref - sent_cand))ctx_align = context_alignment(context or "", candidate or "")term_info = terminology_consistency(reference or "", candidate or "")term_score = term_info["score"]combined = weights["overlap"]*bleu + weights["sentiment"]*sent_align + weights["context"]*ctx_align + weights["terminology"]*term_scorereturn {"bleu": round(bleu, 6),"sentiment_align": round(sent_align, 6),"context_align": round(ctx_align, 6),"terminology_score": round(term_score, 6),"final_score": round(combined, 6),"term_info": term_info}# -----------------------------# Batch processing utilities# -----------------------------def process_dataframe(df, N, weights, text_columns=("reference","candidate","context")):rows = []for idx, row in df.iterrows():ref = row.get(text_columns[0], "") if text_columns[0] in row else row.get("reference","")cand = row.get(text_columns[1], "") if text_columns[1] in row else row.get("candidate","")ctx = row.get(text_columns[2], "") if text_columns[2] in row else row.get("context","")res = compute_row(ref, cand, ctx, N, weights)rows.append({"reference": ref,"candidate": cand,"context": ctx,"BLEU_like_pct": int(round(res["bleu"]*100)),"SentimentAlign_pct": int(round(res["sentiment_align"]*100)),"ContextAlign_pct": int(round(res["context_align"]*100)),"Terminology_pct": int(round(res["terminology_score"]*100)),"AdaptivityScore_pct": int(round(res["final_score"]*100))})out = pd.DataFrame(rows)return out# -----------------------------# Gradio app functions: single eval, batch CSV, download# -----------------------------def evaluate_single(reference, candidate, context, N, w_overlap, w_sent, w_ctx, w_term):weights = {"overlap": w_overlap, "sentiment": w_sent, "context": w_ctx, "terminology": w_term}s = sum(weights.values())if s>0:weights = {k: v/s for k,v in weights.items()}res = compute_row(reference or "", candidate or "", context or "", N, weights)return {"BLEU_like_pct": int(round(res["bleu"]*100)),"SentimentAlign_pct": int(round(res["sentiment_align"]*100)),"ContextAlign_pct": int(round(res["context_align"]*100)),"Terminology_pct": int(round(res["terminology_score"]*100)),"AdaptivityScore_pct": int(round(res["final_score"]*100)),"TermDetails": res["term_info"]}def process_csv(file_obj, N, w_overlap, w_sent, w_ctx, w_term):if file_obj is None:return pd.DataFrame(), Nonetry:if hasattr(file_obj, "name") and str(file_obj.name).lower().endswith(".csv"):df = pd.read_csv(file_obj)else:df = pd.read_csv(file_obj.name)except Exception as e:return pd.DataFrame({"error":[f"Failed to read CSV: {e}"]}), Nonefor col in ("reference","candidate","context"):if col not in df.columns:df[col] = ""weights = {"overlap": w_overlap, "sentiment": w_sent, "context": w_ctx, "terminology": w_term}s = sum(weights.values())if s>0:weights = {k: v/s for k,v in weights.items()}out_df = process_dataframe(df, N, weights)csv_bytes = out_df.to_csv(index=False).encode("utf-8")bio = BytesIO(csv_bytes)bio.name = "contextual_adaptivity_results.csv"return out_df, bio# -----------------------------# Gradio UI# -----------------------------title_md = """# Contextual Adaptivity Evaluator — Final VersionUpload CSV or use single-mode. Outputs: BLEU-like overlap, sentiment alignment, context alignment, terminology consistency, and a combined Adaptivity score."""with gr.Blocks(title="Contextual Adaptivity Evaluator") as demo:gr.Markdown(title_md)with gr.Tabs():with gr.TabItem("Single Eval"):with gr.Row():with gr.Column(scale=7):ctx = gr.Textbox(lines=3, label="Context (scenario)", placeholder="Describe the scenario or conversation..." )ref = gr.Textbox(lines=2, label="Reference (gold)")cand = gr.Textbox(lines=2, label="Candidate (model output)")with gr.Row():N = gr.Slider(1,6,value=4,step=1,label="n-gram N")w_ov = gr.Number(value=0.4, label="weight: overlap")w_sent = gr.Number(value=0.25, label="weight: sentiment")w_ctx = gr.Number(value=0.2, label="weight: context")w_term = gr.Number(value=0.15, label="weight: terminology")btn_eval = gr.Button("Evaluate")with gr.Column(scale=5):out_json = gr.JSON(label="Result (single)", interactive=False)btn_eval.click(evaluate_single, inputs=[ref,cand,ctx,N,w_ov,w_sent,w_ctx,w_term], outputs=[out_json])with gr.TabItem("Batch CSV / Table"):gr.Markdown("Upload a CSV file with columns: reference, candidate, context (headers optional). The Space will compute row-wise scores and return a results CSV.")with gr.Row():file_in = gr.File(label="Upload CSV (reference,candidate,context)")with gr.Column(scale=3):N2 = gr.Slider(1,6,value=4,step=1,label="n-gram N")w_ov2 = gr.Number(value=0.4, label="weight: overlap")w_sent2 = gr.Number(value=0.25, label="weight: sentiment")w_ctx2 = gr.Number(value=0.2, label="weight: context")w_term2 = gr.Number(value=0.15, label="weight: terminology")btn_process = gr.Button("Process CSV / Compute Table")table = gr.Dataframe(headers=["reference","candidate","context","BLEU_like_pct","SentimentAlign_pct","ContextAlign_pct","Terminology_pct","AdaptivityScore_pct"], datatype=["str","str","str","number","number","number","number","number"])csv_out = gr.File(label="Download Results (CSV)")status = gr.Label(value="Ready")def process_and_return(file_obj, N, ov, sent, ctx, term):df, bio = process_csv(file_obj, N, ov, sent, ctx, term)if bio is None:return df, None, "Failed: check logs"return df, bio, f"Done — {len(df)} rows processed"btn_process.click(process_and_return, inputs=[file_in,N2,w_ov2,w_sent2,w_ctx2,w_term2], outputs=[table,csv_out,status])gr.Markdown("---\n**Notes & tips**: Make sure you set a Secrets variable named `HF_API_TOKEN` in Space Settings → Secrets. This Space uses the Hugging Face Inference API for embeddings and sentiment (fast and memory-light).")if __name__ == "__main__":demo.launch()
1234gradio>=3.8pandasnumpyrequests
upload/README.md.txt+28
upload/app.py.txt+304
upload/requirements.txt.txt+4