Spaces:
Running
Running
fix(writing): use top_k=None in text-classification pipeline and add structured feedback fields
Browse files67 unmodified lines686970717172737421 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231249 unmodified lines1341351361371381391401411421431441453 unmodified lines14915015115215315415515615771 unmodified lines22923023120623223323423523623723823924024124224324424524624724824925025125225325425525678 unmodified lines33533633729229333833934034134234334434534634734834935035111 unmodified lines3633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174185 unmodified lines42442542632242742842943043143243319 unmodified lines4534544553484564574584596 unmodified lines46646746836146947047147261 unmodified lines53453553642953753853954054154254354454554654754867 unmodified lines print(f"Loading {task_name}: {model_id}...") pipelines[task_name] = pipeline( "text-classification", model=model_id, tokenizer=model_id, device=DEVICE, return_all_scores=True device=DEVICE, top_k=None ) print(f"Loaded {task_name}.") except Exception as e:21 unmodified lines lexicalResource: str grammaticalRange: str
class WritingCorrection(BaseModel): original: str corrected: str sentence_original: Optional[str] = None sentence_corrected: Optional[str] = None category: str = "grammar" label: str = "Grammar" explanation: str = ""
class LanguageUpgrade(BaseModel): original: str upgraded: str reason: str = ""
class WritingResponse(BaseModel): overallScore: float imageDescription: Optional[str] = None criteriaScores: WritingScores shortFeedback: ShortFeedbackWriting detailedFeedback: str corrections: List[WritingCorrection] = Field(default_factory=list) languageUpgrades: List[LanguageUpgrade] = Field(default_factory=list) upgradedVersion: Optional[str] = None
class SpeakingScores(BaseModel): fluencyCoherence: float9 unmodified lines is_correct: bool error_type: Optional[str] = None
class SpeechMetrics(BaseModel): wpm: float = 0.0 pause_ratio: float = 0.0 duration_seconds: float = 0.0 word_count: int = 0
class SpeakingResponse(BaseModel): overallScore: float transcript: str3 unmodified lines shortFeedback: dict detailedFeedback: str pronunciationBreakdown: List[PronunciationWord] speechMetrics: Optional[SpeechMetrics] = None expectedIpa: Optional[str] = None actualIpa: Optional[str] = None
def round_to_half(score: float) -> float: return round(score * 2) / 271 unmodified lines "Lexical Resource": "...", "Grammatical Range and Accuracy": "..." }}, "detailedFeedback": "MARKDOWN STRING..." "detailedFeedback": "MARKDOWN STRING...", "corrections": [ {{ "original": "exact wrong substring from essay", "corrected": "corrected substring", "sentence_original": "full original sentence containing the error", "sentence_corrected": "full corrected sentence", "category": "grammar | vocabulary | spelling | coherence | task", "label": "short tag e.g. Verb Tense, Collocation, Spelling", "explanation": "concise bilingual or Vietnamese explanation" }} ], "languageUpgrades": [ {{ "original": "informal or weak phrase from essay", "upgraded": "academic Band 8+ equivalent", "reason": "why the upgrade improves Lexical Resource or tone" }} ], "upgradedVersion": "A complete, cohesive Band 8.0+ rewrite of the student essay." }} Include 4-8 high-impact items in "corrections" and 3-5 items in "languageUpgrades" using exact substrings from the essay so UI highlighting can match them reliably. """ payload = {78 unmodified lines else: final_input = f"{request.prompt} [SEP] {request.essay}"
results = model(final_input, truncation=True, max_length=512)[0] raw = {item['label']: item['score'] for item in results} raw_out = model(final_input, truncation=True, max_length=512) results = ( raw_out[0] if isinstance(raw_out, list) and raw_out and isinstance(raw_out[0], list) else (raw_out if isinstance(raw_out, list) else [raw_out]) ) raw = { item['label']: item['score'] for item in results if isinstance(item, dict) and 'label' in item } def r(x): return round(x * 2) / 2 11 unmodified lines sf = fb.get("shortFeedback", {}) tr_fb = sf.get("Task Response") or sf.get("Task Achievement") or "No feedback"
parsed_corrections: List[WritingCorrection] = [] raw_corrections = fb.get("corrections") if isinstance(raw_corrections, list): for item in raw_corrections: if not isinstance(item, dict): continue orig = item.get("original") corr = item.get("corrected") if not isinstance(orig, str) or not isinstance(corr, str) or not orig.strip(): continue try: parsed_corrections.append( WritingCorrection( original=orig, corrected=corr, sentence_original=item.get("sentence_original"), sentence_corrected=item.get("sentence_corrected"), category=str(item.get("category") or "grammar"), label=str(item.get("label") or "Grammar"), explanation=str(item.get("explanation") or ""), ) ) except Exception: continue
parsed_upgrades: List[LanguageUpgrade] = [] raw_upgrades = fb.get("languageUpgrades") if isinstance(raw_upgrades, list): for item in raw_upgrades: if not isinstance(item, dict): continue orig = item.get("original") upg = item.get("upgraded") if not isinstance(orig, str) or not isinstance(upg, str) or not orig.strip(): continue try: parsed_upgrades.append( LanguageUpgrade( original=orig, upgraded=upg, reason=str(item.get("reason") or ""), ) ) except Exception: continue
upgraded_version = fb.get("upgradedVersion") if not isinstance(upgraded_version, str): upgraded_version = None return WritingResponse( overallScore=overall,5 unmodified lines lexicalResource=sf.get("Lexical Resource", ""), grammaticalRange=sf.get("Grammatical Range and Accuracy", "") ), detailedFeedback=fb.get("detailedFeedback", "") detailedFeedback=fb.get("detailedFeedback", ""), corrections=parsed_corrections, languageUpgrades=parsed_upgrades, upgradedVersion=upgraded_version, )
async def grade_speaking_with_gpt(transcript: str, metrics: dict, ipa_data: dict, prompt_text: str) -> dict:19 unmodified lines 1. Score the 4 criteria (0-9). 2. **Pronunciation Breakdown**: Map words from Transcript to the IPA. Identify mispronounced words. - Compare Actual vs Expected IPA for each word. - Assign a score (1-10) for each word's pronunciation. - Assign an integer score (0-100 percentage, where 100 is native accuracy and < 70 needs improvement) for each word's pronunciation. - Flag errors (e.g., 'severe_substitution' if user said 'trip' but meant 'subject'). OUTPUT JSON FORMAT (This is sample structure, replace with actual data):6 unmodified lines "pronunciationBreakdown": [ {{ "word": "subject", "score": 3, "score": 35, "phonemes_expected": "s ʌ b dʒ ɛ k t", "phonemes_actual": "t r ɪ p", "is_correct": false,61 unmodified lines criteriaScores=criteria, shortFeedback=gpt_result.get("shortFeedback", {}), detailedFeedback=gpt_result.get("detailedFeedback", ""), pronunciationBreakdown=gpt_result.get("pronunciationBreakdown", []) pronunciationBreakdown=gpt_result.get("pronunciationBreakdown", []), speechMetrics=SpeechMetrics( wpm=round(float(wpm), 1), pause_ratio=round(float(pause_ratio), 3), duration_seconds=round(float(duration), 1), word_count=int(word_count), ), expectedIpa=ipa_data.get("expected_ipa") if isinstance(ipa_data, dict) else None, actualIpa=ipa_data.get("actual_ipa") if isinstance(ipa_data, dict) else None, )
except Exception as e:src/api.py+124-8