Spaces:
Sleeping
Sleeping
Update tinyllama_inference.py
Browse files- tinyllama_inference.py +43 -44
tinyllama_inference.py
CHANGED
@@ -1,44 +1,43 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
import
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
tokenizer
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
tokenizer,
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
result
|
44 |
-
print(json.dumps(result))
|
|
|
1 |
+
import json
|
2 |
+
import torch
|
3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
4 |
+
|
5 |
+
def load_model():
|
6 |
+
# Use a public model for code evaluation.
|
7 |
+
model_name = "Salesforce/codegen-350M-mono"
|
8 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
9 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
10 |
+
return tokenizer, model
|
11 |
+
|
12 |
+
def evaluate_code(question, code):
|
13 |
+
# Construct a prompt for the AI evaluator.
|
14 |
+
prompt = f"""
|
15 |
+
You are an expert code evaluator.
|
16 |
+
Rate the user's solution to the following problem from 0-5 (0 = completely incorrect, 5 = excellent).
|
17 |
+
Also provide a concise "feedback" message.
|
18 |
+
Problem: "{question}"
|
19 |
+
Solution: "{code}"
|
20 |
+
Return ONLY valid JSON: {{"stars": number, "feedback": string}}
|
21 |
+
Do not include any extra text outside the JSON.
|
22 |
+
"""
|
23 |
+
# Load the model and tokenizer.
|
24 |
+
tokenizer, model = load_model()
|
25 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
26 |
+
outputs = model.generate(**inputs, max_new_tokens=150)
|
27 |
+
response_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
28 |
+
try:
|
29 |
+
result = json.loads(response_text.strip())
|
30 |
+
except Exception as e:
|
31 |
+
result = {"stars": 0, "feedback": "Evaluation failed. Unable to parse AI response."}
|
32 |
+
return result
|
33 |
+
|
34 |
+
# For direct testing from the command line
|
35 |
+
if __name__ == "__main__":
|
36 |
+
import sys
|
37 |
+
if len(sys.argv) < 3:
|
38 |
+
print(json.dumps({"error": "Please provide a question and code as arguments"}))
|
39 |
+
sys.exit(1)
|
40 |
+
question = sys.argv[1]
|
41 |
+
code = sys.argv[2]
|
42 |
+
result = evaluate_code(question, code)
|
43 |
+
print(json.dumps(result))
|
|