Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -1,67 +1,57 @@
|
|
1 |
from flask import Flask, request, jsonify
|
2 |
import torch
|
3 |
-
from transformers import RobertaTokenizer
|
4 |
import os
|
|
|
|
|
5 |
|
|
|
6 |
app = Flask(__name__)
|
7 |
|
8 |
-
# Load model and tokenizer
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
config = RobertaConfig.from_dict(checkpoint['config'])
|
13 |
-
|
14 |
-
# Initialize model with loaded config
|
15 |
-
model = RobertaForSequenceClassification(config)
|
16 |
-
model.load_state_dict(checkpoint['model_state_dict'])
|
17 |
-
model.eval()
|
18 |
-
return model
|
19 |
|
20 |
-
#
|
21 |
-
|
22 |
-
tokenizer = RobertaTokenizer.from_pretrained("./tokenizer")
|
23 |
-
model = load_model()
|
24 |
-
print("Model and tokenizer loaded successfully!")
|
25 |
-
except Exception as e:
|
26 |
-
print(f"Error loading model: {str(e)}")
|
27 |
|
28 |
@app.route("/")
|
29 |
def home():
|
30 |
-
return
|
31 |
|
32 |
@app.route("/predict", methods=["POST"])
|
33 |
def predict():
|
34 |
try:
|
35 |
-
#
|
|
|
36 |
data = request.get_json()
|
37 |
if "code" not in data:
|
38 |
return jsonify({"error": "Missing 'code' parameter"}), 400
|
39 |
|
40 |
-
|
41 |
|
42 |
-
# Tokenize input
|
43 |
inputs = tokenizer(
|
44 |
-
|
|
|
45 |
truncation=True,
|
46 |
padding='max_length',
|
47 |
-
max_length=512
|
48 |
-
return_tensors='pt'
|
49 |
)
|
50 |
|
51 |
-
# Make prediction
|
52 |
with torch.no_grad():
|
53 |
outputs = model(**inputs)
|
|
|
|
|
|
|
|
|
54 |
|
55 |
-
|
56 |
-
score = torch.sigmoid(outputs.logits).item()
|
57 |
-
|
58 |
-
return jsonify({
|
59 |
-
"readability_score": round(score, 4),
|
60 |
-
"processed_code": code[:500] + "..." if len(code) > 500 else code
|
61 |
-
})
|
62 |
-
|
63 |
except Exception as e:
|
64 |
return jsonify({"error": str(e)}), 500
|
65 |
|
|
|
66 |
if __name__ == "__main__":
|
67 |
app.run(host="0.0.0.0", port=7860)
|
|
|
1 |
from flask import Flask, request, jsonify
|
2 |
import torch
|
3 |
+
from transformers import RobertaTokenizer
|
4 |
import os
|
5 |
+
from transformers import RobertaForSequenceClassification
|
6 |
+
import torch.serialization
|
7 |
|
8 |
+
# Initialize Flask app
|
9 |
app = Flask(__name__)
|
10 |
|
11 |
+
# Load the trained model and tokenizer
|
12 |
+
tokenizer = RobertaTokenizer.from_pretrained("microsoft/codebert-base")
|
13 |
+
torch.serialization.add_safe_globals([RobertaForSequenceClassification])
|
14 |
+
model = torch.load("model.pth", map_location=torch.device('cpu'), weights_only=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
+
# Ensure the model is in evaluation mode
|
17 |
+
model.eval()
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
@app.route("/")
|
20 |
def home():
|
21 |
+
return request.url
|
22 |
|
23 |
@app.route("/predict", methods=["POST"])
|
24 |
def predict():
|
25 |
try:
|
26 |
+
# Debugging: print input code to check if the request is received correctly
|
27 |
+
print("Received code:", request.get_json()["code"])
|
28 |
data = request.get_json()
|
29 |
if "code" not in data:
|
30 |
return jsonify({"error": "Missing 'code' parameter"}), 400
|
31 |
|
32 |
+
code_input = data["code"]
|
33 |
|
34 |
+
# Tokenize the input code using the CodeBERT tokenizer
|
35 |
inputs = tokenizer(
|
36 |
+
code_input,
|
37 |
+
return_tensors='pt',
|
38 |
truncation=True,
|
39 |
padding='max_length',
|
40 |
+
max_length=512
|
|
|
41 |
)
|
42 |
|
43 |
+
# Make prediction using the model
|
44 |
with torch.no_grad():
|
45 |
outputs = model(**inputs)
|
46 |
+
prediction = outputs.logits.squeeze().item()
|
47 |
+
|
48 |
+
# Extract the predicted score (single float)
|
49 |
+
print(f"Predicted score: {prediction}") # Debugging: Print prediction
|
50 |
|
51 |
+
return jsonify({"predicted_score": prediction})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
except Exception as e:
|
53 |
return jsonify({"error": str(e)}), 500
|
54 |
|
55 |
+
# Run the Flask app
|
56 |
if __name__ == "__main__":
|
57 |
app.run(host="0.0.0.0", port=7860)
|