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89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#!/usr/bin/env python3
"""
Strict Evaluation Script for Fine-tuned Qwen3-8B DoRA Model

Tests:
1. Factual Accuracy - Does it return correct facts from training data?
2. Hallucination Detection - Does it make up facts about unknown areas?
3. Consistency - Same question, same answer?
4. Format Quality - Proper response structure?
5. Coverage - Can it answer across all categories?
"""

import json
import random
import torch
from pathlib import Path
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
from collections import defaultdict
import re

# Ground truth test cases (from training data)
FACTUAL_TESTS = [
    {
        "question": "What is the population density of Khlong Toei?",
        "expected_keywords": ["population", "density", "khlong toei"],
        "category": "demographics"
    },
    {
        "question": "Is fiber internet available in Thong Lo?",
        "expected_keywords": ["fiber", "internet", "available", "thong lo"],
        "category": "telecom"
    },
    {
        "question": "What type of housing is common in Sathorn?",
        "expected_keywords": ["condo", "housing", "sathorn"],
        "category": "housing"
    },
    {
        "question": "How safe is Ari at night?",
        "expected_keywords": ["safe", "ari", "night"],
        "category": "safety"
    },
    {
        "question": "What is the average condo price in Sukhumvit?",
        "expected_keywords": ["price", "condo", "baht", "sukhumvit"],
        "category": "property"
    },
    {
        "question": "Does Lat Phrao have good BTS access?",
        "expected_keywords": ["bts", "mrt", "transit", "lat phrao"],
        "category": "transport"
    },
    {
        "question": "What is the expat population like in Ekkamai?",
        "expected_keywords": ["expat", "foreigner", "ekkamai"],
        "category": "demographics"
    },
    {
        "question": "Are there international schools near Ari?",
        "expected_keywords": ["school", "international", "education", "ari"],
        "category": "education"
    },
    {
        "question": "What's the air quality like in Bang Kapi?",
        "expected_keywords": ["air", "quality", "aqi", "bang kapi"],
        "category": "environment"
    },
    {
        "question": "Is Phra Khanong good for families?",
        "expected_keywords": ["family", "families", "phra khanong"],
        "category": "lifestyle"
    },
]

# Hallucination tests - areas that DON'T exist or aren't in BMR
HALLUCINATION_TESTS = [
    {
        "question": "What is the population of Zarathon district?",
        "should_admit_unknown": True,
        "fake_area": "Zarathon"
    },
    {
        "question": "Is Moonville in Bangkok expensive?",
        "should_admit_unknown": True,
        "fake_area": "Moonville"
    },
    {
        "question": "Tell me about Krungthep Noi subdistrict",
        "should_admit_unknown": True,
        "fake_area": "Krungthep Noi"
    },
]

# Comparison tests
COMPARISON_TESTS = [
    {
        "question": "Compare Thong Lo and Ekkamai for expats",
        "expected_mentions": ["thong lo", "ekkamai"],
        "category": "comparison"
    },
    {
        "question": "Which is cheaper, Ari or Sathorn?",
        "expected_mentions": ["ari", "sathorn", "price", "cheaper"],
        "category": "comparison"
    },
]

# Recommendation tests
RECOMMENDATION_TESTS = [
    {
        "question": "Best area for young professionals near BTS?",
        "should_recommend_area": True,
        "category": "recommendation"
    },
    {
        "question": "Where should a family with kids live in Bangkok?",
        "should_recommend_area": True,
        "category": "recommendation"
    },
    {
        "question": "Affordable areas with good transit?",
        "should_recommend_area": True,
        "category": "recommendation"
    },
]


def load_model(model_path: str, base_model: str = "Qwen/Qwen3-8B"):
    """Load the fine-tuned model."""
    print(f"Loading base model: {base_model}")
    
    tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
    
    model = AutoModelForCausalLM.from_pretrained(
        base_model,
        trust_remote_code=True,
        torch_dtype=torch.bfloat16,
        device_map="auto",
    )
    
    print(f"Loading DoRA adapter from: {model_path}")
    model = PeftModel.from_pretrained(model, model_path)
    model.eval()
    
    return model, tokenizer


def generate_response(model, tokenizer, question: str, max_new_tokens: int = 256):
    """Generate a response."""
    messages = [
        {"role": "system", "content": "You are a Thailand real estate and neighborhood expert for Bangkok Metropolitan Region."},
        {"role": "user", "content": question}
    ]
    
    prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
    
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_new_tokens=max_new_tokens,
            temperature=0.3,  # Lower temp for more deterministic eval
            top_p=0.9,
            do_sample=True,
            pad_token_id=tokenizer.eos_token_id,
        )
    
    response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True)
    return response.strip()


def check_keywords(response: str, keywords: list) -> tuple:
    """Check if response contains expected keywords."""
    response_lower = response.lower()
    found = []
    missing = []
    for kw in keywords:
        if kw.lower() in response_lower:
            found.append(kw)
        else:
            missing.append(kw)
    return found, missing


def check_hallucination(response: str, fake_area: str) -> bool:
    """Check if model admits it doesn't know about fake area."""
    uncertainty_phrases = [
        "don't have information",
        "not familiar",
        "don't know",
        "no data",
        "cannot find",
        "not aware",
        "doesn't exist",
        "not a real",
        "unable to find",
        "no information",
        "i'm not sure",
        "i don't have",
    ]
    response_lower = response.lower()
    
    # Check if it admits uncertainty
    admits_unknown = any(phrase in response_lower for phrase in uncertainty_phrases)
    
    # Check if it confidently makes up facts (bad)
    confident_phrases = ["population of", "located in", "has a density", "is known for", "residents live"]
    makes_up_facts = any(phrase in response_lower for phrase in confident_phrases)
    
    return admits_unknown or not makes_up_facts


def check_recommendation(response: str) -> bool:
    """Check if response provides actual area recommendations."""
    # Common Bangkok areas
    areas = ["ari", "thong lo", "ekkamai", "sathorn", "silom", "sukhumvit", 
             "lat phrao", "bang kapi", "ratchada", "phra khanong", "on nut",
             "bang na", "rama 9", "asok", "phrom phong", "nana"]
    response_lower = response.lower()
    return any(area in response_lower for area in areas)


def run_consistency_test(model, tokenizer, question: str, n_runs: int = 3) -> float:
    """Check if model gives consistent answers."""
    responses = []
    for _ in range(n_runs):
        resp = generate_response(model, tokenizer, question)
        responses.append(resp.lower())
    
    # Simple consistency: check if key facts are mentioned in all responses
    # Extract numbers and area names mentioned
    all_words = [set(re.findall(r'\b\w+\b', r)) for r in responses]
    common_words = set.intersection(*all_words) if all_words else set()
    
    # Higher ratio of common words = more consistent
    avg_len = sum(len(w) for w in all_words) / len(all_words)
    consistency = len(common_words) / avg_len if avg_len > 0 else 0
    
    return consistency


def evaluate(model_path: str):
    """Run full evaluation."""
    model, tokenizer = load_model(model_path)
    
    results = {
        "factual": {"passed": 0, "total": 0, "details": []},
        "hallucination": {"passed": 0, "total": 0, "details": []},
        "comparison": {"passed": 0, "total": 0, "details": []},
        "recommendation": {"passed": 0, "total": 0, "details": []},
        "consistency": {"scores": [], "details": []},
    }
    
    print("\n" + "=" * 70)
    print("STRICT EVALUATION - Fine-tuned Qwen3-8B DoRA")
    print("=" * 70)
    
    # 1. Factual Tests
    print("\n[1/5] FACTUAL ACCURACY TESTS")
    print("-" * 50)
    for test in FACTUAL_TESTS:
        response = generate_response(model, tokenizer, test["question"])
        found, missing = check_keywords(response, test["expected_keywords"])
        passed = len(missing) <= 1  # Allow 1 missing keyword
        
        results["factual"]["total"] += 1
        if passed:
            results["factual"]["passed"] += 1
        
        status = "✓ PASS" if passed else "✗ FAIL"
        print(f"\nQ: {test['question']}")
        print(f"A: {response[:200]}..." if len(response) > 200 else f"A: {response}")
        print(f"Keywords found: {found}, missing: {missing}")
        print(f"[{status}]")
        
        results["factual"]["details"].append({
            "question": test["question"],
            "response": response,
            "passed": passed,
            "found": found,
            "missing": missing
        })
    
    # 2. Hallucination Tests
    print("\n\n[2/5] HALLUCINATION DETECTION TESTS")
    print("-" * 50)
    for test in HALLUCINATION_TESTS:
        response = generate_response(model, tokenizer, test["question"])
        passed = check_hallucination(response, test["fake_area"])
        
        results["hallucination"]["total"] += 1
        if passed:
            results["hallucination"]["passed"] += 1
        
        status = "✓ PASS" if passed else "✗ FAIL (hallucinated)"
        print(f"\nQ: {test['question']}")
        print(f"A: {response[:200]}..." if len(response) > 200 else f"A: {response}")
        print(f"[{status}]")
        
        results["hallucination"]["details"].append({
            "question": test["question"],
            "response": response,
            "passed": passed,
            "fake_area": test["fake_area"]
        })
    
    # 3. Comparison Tests
    print("\n\n[3/5] COMPARISON TESTS")
    print("-" * 50)
    for test in COMPARISON_TESTS:
        response = generate_response(model, tokenizer, test["question"])
        found, missing = check_keywords(response, test["expected_mentions"])
        passed = len(missing) == 0
        
        results["comparison"]["total"] += 1
        if passed:
            results["comparison"]["passed"] += 1
        
        status = "✓ PASS" if passed else "✗ FAIL"
        print(f"\nQ: {test['question']}")
        print(f"A: {response[:300]}..." if len(response) > 300 else f"A: {response}")
        print(f"[{status}]")
        
        results["comparison"]["details"].append({
            "question": test["question"],
            "response": response,
            "passed": passed
        })
    
    # 4. Recommendation Tests
    print("\n\n[4/5] RECOMMENDATION TESTS")
    print("-" * 50)
    for test in RECOMMENDATION_TESTS:
        response = generate_response(model, tokenizer, test["question"])
        passed = check_recommendation(response)
        
        results["recommendation"]["total"] += 1
        if passed:
            results["recommendation"]["passed"] += 1
        
        status = "✓ PASS" if passed else "✗ FAIL"
        print(f"\nQ: {test['question']}")
        print(f"A: {response[:300]}..." if len(response) > 300 else f"A: {response}")
        print(f"[{status}]")
        
        results["recommendation"]["details"].append({
            "question": test["question"],
            "response": response,
            "passed": passed
        })
    
    # 5. Consistency Tests
    print("\n\n[5/5] CONSISTENCY TESTS")
    print("-" * 50)
    consistency_questions = [
        "What is the average rent in Thong Lo?",
        "Is Ari a good area for expats?",
    ]
    for q in consistency_questions:
        score = run_consistency_test(model, tokenizer, q)
        results["consistency"]["scores"].append(score)
        print(f"\nQ: {q}")
        print(f"Consistency score: {score:.2%}")
    
    # Summary
    print("\n\n" + "=" * 70)
    print("EVALUATION SUMMARY")
    print("=" * 70)
    
    factual_score = results["factual"]["passed"] / results["factual"]["total"] * 100
    halluc_score = results["hallucination"]["passed"] / results["hallucination"]["total"] * 100
    compare_score = results["comparison"]["passed"] / results["comparison"]["total"] * 100
    recommend_score = results["recommendation"]["passed"] / results["recommendation"]["total"] * 100
    consistency_avg = sum(results["consistency"]["scores"]) / len(results["consistency"]["scores"]) * 100 if results["consistency"]["scores"] else 0
    
    print(f"\n1. Factual Accuracy:      {results['factual']['passed']}/{results['factual']['total']} ({factual_score:.1f}%)")
    print(f"2. Hallucination Control: {results['hallucination']['passed']}/{results['hallucination']['total']} ({halluc_score:.1f}%)")
    print(f"3. Comparison Ability:    {results['comparison']['passed']}/{results['comparison']['total']} ({compare_score:.1f}%)")
    print(f"4. Recommendations:       {results['recommendation']['passed']}/{results['recommendation']['total']} ({recommend_score:.1f}%)")
    print(f"5. Consistency:           {consistency_avg:.1f}%")
    
    overall = (factual_score + halluc_score + compare_score + recommend_score + consistency_avg) / 5
    print(f"\n{'='*50}")
    print(f"OVERALL SCORE: {overall:.1f}%")
    print(f"{'='*50}")
    
    # Grade
    if overall >= 90:
        grade = "A - Excellent"
    elif overall >= 80:
        grade = "B - Good"
    elif overall >= 70:
        grade = "C - Acceptable"
    elif overall >= 60:
        grade = "D - Needs Improvement"
    else:
        grade = "F - Failed"
    
    print(f"GRADE: {grade}")
    
    # Save results
    with open("/root/qa-finetune/outputs/eval_results.json", "w") as f:
        json.dump(results, f, indent=2)
    print(f"\nDetailed results saved to: /root/qa-finetune/outputs/eval_results.json")
    
    return results


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--model_path", type=str, default="/root/qa-finetune/outputs/qwen3-4b-dora/final")
    args = parser.parse_args()
    
    evaluate(args.model_path)