Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,143 +1,187 @@
|
|
| 1 |
import json
|
| 2 |
import tempfile
|
| 3 |
-
from typing import List, Dict, Any
|
| 4 |
|
| 5 |
import gradio as gr
|
| 6 |
-
from transformers import pipeline
|
| 7 |
-
|
| 8 |
-
#
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
def
|
| 28 |
"""
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
| 31 |
"""
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
if
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
if
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
# Çok kısa cevapları minimal genişletme
|
| 53 |
-
if len(a2.split()) < 5:
|
| 54 |
-
a2 = a2 + " This answer has been clarified for brevity and precision."
|
| 55 |
-
|
| 56 |
-
item["question"] = q2
|
| 57 |
-
item["answer"] = a2
|
| 58 |
return item
|
| 59 |
|
| 60 |
def process_json(
|
| 61 |
-
file,
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
)
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
data = json.load(open(file.name))
|
| 67 |
items: List[Dict[str, Any]] = data if isinstance(data, list) else [data]
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
def needs_improve(lbl: str) -> bool:
|
| 75 |
-
if
|
|
|
|
|
|
|
| 76 |
return lbl == "low"
|
| 77 |
-
|
| 78 |
return lbl in ("low", "medium")
|
| 79 |
return False
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
# Özet tablo için küçük bir görünüm (id yoksa index)
|
| 92 |
summary = []
|
| 93 |
-
for
|
|
|
|
|
|
|
| 94 |
summary.append({
|
| 95 |
-
"id": it.get("id",
|
| 96 |
-
"
|
| 97 |
-
"
|
|
|
|
|
|
|
| 98 |
"question_preview": (it.get("question") or "")[:120]
|
| 99 |
})
|
| 100 |
|
| 101 |
-
# İndirilebilir
|
| 102 |
-
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".json", mode="w")
|
| 103 |
json.dump(scored, tmp, indent=2, ensure_ascii=False)
|
| 104 |
-
tmp.flush()
|
| 105 |
-
tmp.close()
|
| 106 |
|
| 107 |
-
#
|
| 108 |
-
|
| 109 |
if len(scored) > 50:
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
return summary,
|
| 113 |
|
| 114 |
with gr.Blocks(title="Q&A Quality Evaluator", theme=gr.themes.Soft()) as demo:
|
| 115 |
-
gr.Markdown("## Q&A Quality Evaluator\nUpload
|
| 116 |
|
| 117 |
with gr.Row():
|
| 118 |
-
|
| 119 |
|
| 120 |
with gr.Row():
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
label="Improve threshold")
|
| 124 |
|
| 125 |
-
|
| 126 |
|
| 127 |
-
gr.
|
| 128 |
-
|
| 129 |
-
|
| 130 |
with gr.Tab("Preview JSON"):
|
| 131 |
-
|
| 132 |
-
out_code = gr.Code(language="json", label="Preview (first 50 items)", interactive=False, lines=30)
|
| 133 |
with gr.Tab("Download"):
|
| 134 |
-
|
|
|
|
| 135 |
|
| 136 |
-
|
| 137 |
-
process_json,
|
| 138 |
-
inputs=[inp_file, auto_switch, improve_sel],
|
| 139 |
-
outputs=[out_table, out_code, out_file]
|
| 140 |
-
)
|
| 141 |
|
| 142 |
if __name__ == "__main__":
|
| 143 |
demo.launch()
|
|
|
|
| 1 |
import json
|
| 2 |
import tempfile
|
| 3 |
+
from typing import List, Dict, Any, Tuple
|
| 4 |
|
| 5 |
import gradio as gr
|
| 6 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
|
| 7 |
+
|
| 8 |
+
# ---------------------------
|
| 9 |
+
# Model init (HF Transformers ile uyumlu)
|
| 10 |
+
# ---------------------------
|
| 11 |
+
MODEL_ID = "OpenAssistant/reward-model-deberta-v3-large-v2"
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
quality_pipe = pipeline(
|
| 15 |
+
task="text-classification",
|
| 16 |
+
model=MODEL_ID,
|
| 17 |
+
tokenizer=MODEL_ID,
|
| 18 |
+
return_all_scores=False,
|
| 19 |
+
function_to_apply="none" # regression; pipelinede score'ı direkt ver
|
| 20 |
+
)
|
| 21 |
+
MODEL_READY = True
|
| 22 |
+
except Exception as e:
|
| 23 |
+
MODEL_READY = False
|
| 24 |
+
LOAD_ERR = str(e)
|
| 25 |
+
|
| 26 |
+
def score_pair(question: str, answer: str) -> float:
|
| 27 |
+
"""
|
| 28 |
+
Reward model prompt-response formatını besliyoruz.
|
| 29 |
+
Bu model regresyon skoru döndürür (daha büyük = daha iyi).
|
| 30 |
+
"""
|
| 31 |
+
if not MODEL_READY:
|
| 32 |
+
# Model yüklenemezse yumuşak yedek: basit heuristik skor
|
| 33 |
+
# (uzunluk, noktalama, soru işareti vs.)
|
| 34 |
+
base = 0.3
|
| 35 |
+
if question.strip().endswith("?"):
|
| 36 |
+
base += 0.1
|
| 37 |
+
if len(answer.split()) >= 6:
|
| 38 |
+
base += 0.2
|
| 39 |
+
if answer.strip().endswith((".", "!", "?")):
|
| 40 |
+
base += 0.1
|
| 41 |
+
return base
|
| 42 |
+
|
| 43 |
+
text = f"Human: {question}\nAssistant: {answer}"
|
| 44 |
+
out = quality_pipe(text, truncation=True)[0]
|
| 45 |
+
# out = {'label': 'LABEL_0', 'score': <float>} -> regression score
|
| 46 |
+
return float(out["score"])
|
| 47 |
+
|
| 48 |
+
def label_from_score(score: float) -> str:
|
| 49 |
+
"""
|
| 50 |
+
Eşikler: reward modellerde aralık veri setine göre değişebilir.
|
| 51 |
+
Pratikte şu ayrımlar iş görüyor:
|
| 52 |
+
>0.6 -> high, 0.3-0.6 -> medium, else -> low
|
| 53 |
+
"""
|
| 54 |
+
if score > 0.6:
|
| 55 |
+
return "high"
|
| 56 |
+
if score > 0.3:
|
| 57 |
+
return "medium"
|
| 58 |
+
return "low"
|
| 59 |
|
| 60 |
+
def improve_light(item: Dict[str, Any]) -> Dict[str, Any]:
|
| 61 |
"""
|
| 62 |
+
LLM kullanmadan hafif iyileştirme (ücretsiz/CPU):
|
| 63 |
+
- soru sonuna '?' ekle, ilk harfi büyüt
|
| 64 |
+
- cevap ilk harfi büyüt, sonuna noktalama koy
|
| 65 |
+
- çok kısa cevapsa 1 cümleyle netleştir
|
| 66 |
"""
|
| 67 |
+
q = (item.get("question") or "").strip()
|
| 68 |
+
a = (item.get("answer") or "").strip()
|
| 69 |
+
|
| 70 |
+
if q:
|
| 71 |
+
if not q.endswith("?"):
|
| 72 |
+
q += "?"
|
| 73 |
+
if q[0].islower():
|
| 74 |
+
q = q[0].upper() + q[1:]
|
| 75 |
+
|
| 76 |
+
if a:
|
| 77 |
+
if a[0].islower():
|
| 78 |
+
a = a[0].upper() + a[1:]
|
| 79 |
+
if a[-1] not in ".!?":
|
| 80 |
+
a += "."
|
| 81 |
+
|
| 82 |
+
if len(a.split()) < 6:
|
| 83 |
+
a = a + " This answer has been clarified for brevity and precision."
|
| 84 |
+
|
| 85 |
+
item["question"] = q
|
| 86 |
+
item["answer"] = a
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
return item
|
| 88 |
|
| 89 |
def process_json(
|
| 90 |
+
file, auto_improve: bool, improve_policy: str
|
| 91 |
+
) -> Tuple[List[Dict[str, Any]], str, str, str]:
|
| 92 |
+
"""
|
| 93 |
+
Girdi: JSON (list veya tek obje)
|
| 94 |
+
Çıktı:
|
| 95 |
+
- özet tablo (DataFrame)
|
| 96 |
+
- önizleme JSON (first 50 items)
|
| 97 |
+
- indirilebilir tam JSON path
|
| 98 |
+
- model yükleme uyarısı
|
| 99 |
+
"""
|
| 100 |
data = json.load(open(file.name))
|
| 101 |
items: List[Dict[str, Any]] = data if isinstance(data, list) else [data]
|
| 102 |
|
| 103 |
+
scored = []
|
| 104 |
+
for idx, raw in enumerate(items):
|
| 105 |
+
item = dict(raw)
|
| 106 |
+
q = item.get("question", "")
|
| 107 |
+
a = item.get("answer", "")
|
| 108 |
|
| 109 |
+
# 1) ilk skor
|
| 110 |
+
s1 = score_pair(q, a)
|
| 111 |
+
lbl1 = label_from_score(s1)
|
| 112 |
+
item["quality"] = {"label": lbl1, "score": round(s1, 3)}
|
| 113 |
+
|
| 114 |
+
# 2) gerekiyorsa iyileştir
|
| 115 |
def needs_improve(lbl: str) -> bool:
|
| 116 |
+
if improve_policy == "none":
|
| 117 |
+
return False
|
| 118 |
+
if improve_policy == "low_only":
|
| 119 |
return lbl == "low"
|
| 120 |
+
if improve_policy == "low_and_medium":
|
| 121 |
return lbl in ("low", "medium")
|
| 122 |
return False
|
| 123 |
|
| 124 |
+
if auto_improve and needs_improve(lbl1):
|
| 125 |
+
item = improve_light(item)
|
| 126 |
+
# 3) tekrar skor
|
| 127 |
+
s2 = score_pair(item.get("question", ""), item.get("answer", ""))
|
| 128 |
+
lbl2 = label_from_score(s2)
|
| 129 |
+
item["quality_after"] = {"label": lbl2, "score": round(s2, 3)}
|
| 130 |
+
|
| 131 |
+
scored.append(item)
|
| 132 |
+
|
| 133 |
+
# Özet
|
|
|
|
| 134 |
summary = []
|
| 135 |
+
for i, it in enumerate(scored):
|
| 136 |
+
qa = it.get("quality", {})
|
| 137 |
+
qa2 = it.get("quality_after")
|
| 138 |
summary.append({
|
| 139 |
+
"id": it.get("id", i),
|
| 140 |
+
"label": qa.get("label"),
|
| 141 |
+
"score": qa.get("score"),
|
| 142 |
+
"label_after": qa2.get("label") if qa2 else None,
|
| 143 |
+
"score_after": qa2.get("score") if qa2 else None,
|
| 144 |
"question_preview": (it.get("question") or "")[:120]
|
| 145 |
})
|
| 146 |
|
| 147 |
+
# İndirilebilir dosya
|
| 148 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".json", mode="w", encoding="utf-8")
|
| 149 |
json.dump(scored, tmp, indent=2, ensure_ascii=False)
|
| 150 |
+
tmp.flush(); tmp.close()
|
|
|
|
| 151 |
|
| 152 |
+
# Önizleme
|
| 153 |
+
preview = json.dumps(scored[:50], indent=2, ensure_ascii=False)
|
| 154 |
if len(scored) > 50:
|
| 155 |
+
preview += "\n\n// NOTE: Showing first 50 items. Download full file below."
|
| 156 |
+
|
| 157 |
+
warn = ""
|
| 158 |
+
if not MODEL_READY:
|
| 159 |
+
warn = f"Warning: model '{MODEL_ID}' could not be loaded, used heuristic scoring. Error: {LOAD_ERR}"
|
| 160 |
|
| 161 |
+
return summary, preview, tmp.name, warn
|
| 162 |
|
| 163 |
with gr.Blocks(title="Q&A Quality Evaluator", theme=gr.themes.Soft()) as demo:
|
| 164 |
+
gr.Markdown("## Q&A Quality Evaluator\nUpload Q&A JSON, get model-based quality scores, and optionally auto-improve low items.")
|
| 165 |
|
| 166 |
with gr.Row():
|
| 167 |
+
inp = gr.File(file_types=[".json"], label="Upload JSON (list of objects)")
|
| 168 |
|
| 169 |
with gr.Row():
|
| 170 |
+
auto = gr.Checkbox(value=False, label="Auto-improve low items (rule-based, no LLM)")
|
| 171 |
+
policy = gr.Radio(choices=["low_only", "low_and_medium", "none"], value="low_only", label="Improve threshold")
|
|
|
|
| 172 |
|
| 173 |
+
run = gr.Button("Run")
|
| 174 |
|
| 175 |
+
with gr.Tab("Summary"):
|
| 176 |
+
tbl = gr.Dataframe(headers=["id","label","score","label_after","score_after","question_preview"],
|
| 177 |
+
wrap=True, height=460)
|
| 178 |
with gr.Tab("Preview JSON"):
|
| 179 |
+
code = gr.Code(language="json", lines=34, label="Preview (first 50 items)")
|
|
|
|
| 180 |
with gr.Tab("Download"):
|
| 181 |
+
dfile = gr.File(label="Download full JSON")
|
| 182 |
+
warnbox = gr.Markdown("")
|
| 183 |
|
| 184 |
+
run.click(process_json, inputs=[inp, auto, policy], outputs=[tbl, code, dfile, warnbox])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
if __name__ == "__main__":
|
| 187 |
demo.launch()
|