Spaces:
Running
Running
fix(writing): use top_k=None in text-classification pipeline and add structured feedback fields
Browse files67 unmodified lines6869707172737421 unmodified lines969798991001011021031041051061079 unmodified lines1171181191201211223 unmodified lines12612712812913013171 unmodified lines20320420520620720820921078 unmodified lines28929029129229329429529611 unmodified lines3083093103113123135 unmodified lines31932032132232332432519 unmodified lines3453463473483493503516 unmodified lines35835936036136236336461 unmodified lines42642742842943043143267 unmodified linesprint(f"Loading {task_name}: {model_id}...")pipelines[task_name] = pipeline("text-classification", model=model_id, tokenizer=model_id,device=DEVICE, return_all_scores=True)print(f"Loaded {task_name}.")except Exception as e:21 unmodified lineslexicalResource: strgrammaticalRange: strclass WritingResponse(BaseModel):overallScore: floatimageDescription: Optional[str] = NonecriteriaScores: WritingScoresshortFeedback: ShortFeedbackWritingdetailedFeedback: strclass SpeakingScores(BaseModel):fluencyCoherence: float9 unmodified linesis_correct: boolerror_type: Optional[str] = Noneclass SpeakingResponse(BaseModel):overallScore: floattranscript: str3 unmodified linesshortFeedback: dictdetailedFeedback: strpronunciationBreakdown: List[PronunciationWord]def round_to_half(score: float) -> float:return round(score * 2) / 271 unmodified lines"Lexical Resource": "...","Grammatical Range and Accuracy": "..."}},"detailedFeedback": "MARKDOWN STRING..."}}"""payload = {78 unmodified lineselse: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}def r(x): return round(x * 2) / 211 unmodified linessf = fb.get("shortFeedback", {})tr_fb = sf.get("Task Response") or sf.get("Task Achievement") or "No feedback"return WritingResponse(overallScore=overall,5 unmodified lineslexicalResource=sf.get("Lexical Resource", ""),grammaticalRange=sf.get("Grammatical Range and Accuracy", "")),detailedFeedback=fb.get("detailedFeedback", ""))async def grade_speaking_with_gpt(transcript: str, metrics: dict, ipa_data: dict, prompt_text: str) -> dict:19 unmodified lines1. 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.- 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,"phonemes_expected": "s ʌ b dʒ ɛ k t","phonemes_actual": "t r ɪ p","is_correct": false,61 unmodified linescriteriaScores=criteria,shortFeedback=gpt_result.get("shortFeedback", {}),detailedFeedback=gpt_result.get("detailedFeedback", ""),pronunciationBreakdown=gpt_result.get("pronunciationBreakdown", []))except Exception as e:67 unmodified lines6869707172737421 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231249 unmodified lines1341351361371381391401411421431441453 unmodified lines14915015115215315415515615771 unmodified lines22923023123223323423523623723823924024124224324424524624724824925025125225325425525678 unmodified lines33533633733833934034134234334434534634734834935035111 unmodified lines3633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174185 unmodified lines42442542642742842943043143243319 unmodified lines4534544554564574584596 unmodified lines46646746846947047147261 unmodified lines53453553653753853954054154254354454554654754867 unmodified linesprint(f"Loading {task_name}: {model_id}...")pipelines[task_name] = pipeline("text-classification", model=model_id, tokenizer=model_id,device=DEVICE, top_k=None)print(f"Loaded {task_name}.")except Exception as e:21 unmodified lineslexicalResource: strgrammaticalRange: strclass WritingCorrection(BaseModel):original: strcorrected: strsentence_original: Optional[str] = Nonesentence_corrected: Optional[str] = Nonecategory: str = "grammar"label: str = "Grammar"explanation: str = ""class LanguageUpgrade(BaseModel):original: strupgraded: strreason: str = ""class WritingResponse(BaseModel):overallScore: floatimageDescription: Optional[str] = NonecriteriaScores: WritingScoresshortFeedback: ShortFeedbackWritingdetailedFeedback: strcorrections: List[WritingCorrection] = Field(default_factory=list)languageUpgrades: List[LanguageUpgrade] = Field(default_factory=list)upgradedVersion: Optional[str] = Noneclass SpeakingScores(BaseModel):fluencyCoherence: float9 unmodified linesis_correct: boolerror_type: Optional[str] = Noneclass SpeechMetrics(BaseModel):wpm: float = 0.0pause_ratio: float = 0.0duration_seconds: float = 0.0word_count: int = 0class SpeakingResponse(BaseModel):overallScore: floattranscript: str3 unmodified linesshortFeedback: dictdetailedFeedback: strpronunciationBreakdown: List[PronunciationWord]speechMetrics: Optional[SpeechMetrics] = NoneexpectedIpa: Optional[str] = NoneactualIpa: Optional[str] = Nonedef round_to_half(score: float) -> float:return round(score * 2) / 271 unmodified lines"Lexical Resource": "...","Grammatical Range and Accuracy": "..."}},"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 lineselse:final_input = f"{request.prompt} [SEP] {request.essay}"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 resultsif isinstance(item, dict) and 'label' in item}def r(x): return round(x * 2) / 211 unmodified linessf = 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):continueorig = item.get("original")corr = item.get("corrected")if not isinstance(orig, str) or not isinstance(corr, str) or not orig.strip():continuetry: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:continueparsed_upgrades: List[LanguageUpgrade] = []raw_upgrades = fb.get("languageUpgrades")if isinstance(raw_upgrades, list):for item in raw_upgrades:if not isinstance(item, dict):continueorig = item.get("original")upg = item.get("upgraded")if not isinstance(orig, str) or not isinstance(upg, str) or not orig.strip():continuetry:parsed_upgrades.append(LanguageUpgrade(original=orig,upgraded=upg,reason=str(item.get("reason") or ""),))except Exception:continueupgraded_version = fb.get("upgradedVersion")if not isinstance(upgraded_version, str):upgraded_version = Nonereturn WritingResponse(overallScore=overall,5 unmodified lineslexicalResource=sf.get("Lexical Resource", ""),grammaticalRange=sf.get("Grammatical Range and Accuracy", "")),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 lines1. 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 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": 35,"phonemes_expected": "s ʌ b dʒ ɛ k t","phonemes_actual": "t r ɪ p","is_correct": false,61 unmodified linescriteriaScores=criteria,shortFeedback=gpt_result.get("shortFeedback", {}),detailedFeedback=gpt_result.get("detailedFeedback", ""),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