athv commited on
Commit
9181a5f
·
verified ·
1 Parent(s): e389ca1

Update server.py

Browse files

fixing model name error

Files changed (1) hide show
  1. server.py +84 -84
server.py CHANGED
@@ -1,85 +1,85 @@
1
- import sys
2
- from flask import Flask, request, jsonify
3
- from flask_cors import CORS
4
- from transformers import pipeline
5
-
6
- # --- 1. Initialize Flask App ---
7
- app = Flask(__name__)
8
- CORS(app)
9
-
10
- # --- 2. Load Your Models ---
11
- print("--- Server is starting ---")
12
- print(f"Python version: {sys.version}")
13
-
14
- optimizer_pipeline = None
15
-
16
- # --- Hugging Face Model Loading ---
17
- try:
18
- # This is the specialist model for Python code generation
19
- model_name = 'model_name = Salesforce/codegen-2B-mono'
20
-
21
- print(f"Loading {model_name} model...")
22
-
23
- # Note: We use 'text-generation' for this model type
24
- hf_task = 'text-generation'
25
-
26
- optimizer_pipeline = pipeline(hf_task, model=model_name)
27
-
28
- print("Hugging Face model loaded successfully.")
29
- print("--- Server is ready. ---")
30
-
31
- except Exception as e_hf:
32
- print(f"--- CRITICAL ERROR loading Hugging Face model: {e_hf} ---")
33
- print("--- Server will not work. ---")
34
-
35
-
36
- # --- 3. Create an API Endpoint ---
37
- @app.route('/optimize', methods=['POST'])
38
- def optimize_code():
39
- print("\n--- Received a request ---")
40
-
41
- if not request.json or 'code' not in request.json:
42
- print("Request error: No 'code' key in JSON.")
43
- return jsonify({'error': 'No code provided'}), 400
44
-
45
- # This 'code_snippet' contains your full "Expert" prompt from VS Code
46
- code_snippet = request.json['code']
47
- print(f"Received prompt length: {len(code_snippet)} chars")
48
-
49
- response_data = {}
50
-
51
- try:
52
- # --- Use Optimizer (Hugging Face) ---
53
- if optimizer_pipeline:
54
- print("Running Hugging Face model...")
55
-
56
- # Run the model.
57
- # max_new_tokens=200 gives it enough space to write the optimized code
58
- opt_result = optimizer_pipeline(code_snippet, max_new_tokens=200)
59
-
60
- # Get the full generated text
61
- full_response = opt_result[0]['generated_text']
62
-
63
- # Clean up: We only want the part AFTER "Optimized Code:"
64
- if "Optimized Code:" in full_response:
65
- clean_optimization = full_response.split("Optimized Code:")[-1].strip()
66
- else:
67
- clean_optimization = full_response
68
-
69
- response_data['optimization'] = clean_optimization
70
- print("Optimization generated successfully.")
71
-
72
- else:
73
- print("Optimizer model is not loaded.")
74
- response_data['optimization'] = "Error: Optimizer model is not loaded on server."
75
-
76
- return jsonify(response_data)
77
-
78
- except Exception as e:
79
- print(f"--- ERROR during prediction: {e} ---")
80
- return jsonify({'error': f'Prediction failed: {e}'}), 500
81
-
82
- # --- 4. Run the Server ---
83
- if __name__ == '__main__':
84
- print("Starting Flask server on http://127.0.0.1:5000")
85
  app.run(debug=True, port=5000)
 
1
+ import sys
2
+ from flask import Flask, request, jsonify
3
+ from flask_cors import CORS
4
+ from transformers import pipeline
5
+
6
+ # --- 1. Initialize Flask App ---
7
+ app = Flask(__name__)
8
+ CORS(app)
9
+
10
+ # --- 2. Load Your Models ---
11
+ print("--- Server is starting ---")
12
+ print(f"Python version: {sys.version}")
13
+
14
+ optimizer_pipeline = None
15
+
16
+ # --- Hugging Face Model Loading ---
17
+ try:
18
+ # This is the specialist model for Python code generation
19
+ model_name = 'Salesforce/codegen-2B-mono'
20
+
21
+ print(f"Loading {model_name} model...")
22
+
23
+ # Note: We use 'text-generation' for this model type
24
+ hf_task = 'text-generation'
25
+
26
+ optimizer_pipeline = pipeline(hf_task, model=model_name)
27
+
28
+ print("Hugging Face model loaded successfully.")
29
+ print("--- Server is ready. ---")
30
+
31
+ except Exception as e_hf:
32
+ print(f"--- CRITICAL ERROR loading Hugging Face model: {e_hf} ---")
33
+ print("--- Server will not work. ---")
34
+
35
+
36
+ # --- 3. Create an API Endpoint ---
37
+ @app.route('/optimize', methods=['POST'])
38
+ def optimize_code():
39
+ print("\n--- Received a request ---")
40
+
41
+ if not request.json or 'code' not in request.json:
42
+ print("Request error: No 'code' key in JSON.")
43
+ return jsonify({'error': 'No code provided'}), 400
44
+
45
+ # This 'code_snippet' contains your full "Expert" prompt from VS Code
46
+ code_snippet = request.json['code']
47
+ print(f"Received prompt length: {len(code_snippet)} chars")
48
+
49
+ response_data = {}
50
+
51
+ try:
52
+ # --- Use Optimizer (Hugging Face) ---
53
+ if optimizer_pipeline:
54
+ print("Running Hugging Face model...")
55
+
56
+ # Run the model.
57
+ # max_new_tokens=200 gives it enough space to write the optimized code
58
+ opt_result = optimizer_pipeline(code_snippet, max_new_tokens=200)
59
+
60
+ # Get the full generated text
61
+ full_response = opt_result[0]['generated_text']
62
+
63
+ # Clean up: We only want the part AFTER "Optimized Code:"
64
+ if "Optimized Code:" in full_response:
65
+ clean_optimization = full_response.split("Optimized Code:")[-1].strip()
66
+ else:
67
+ clean_optimization = full_response
68
+
69
+ response_data['optimization'] = clean_optimization
70
+ print("Optimization generated successfully.")
71
+
72
+ else:
73
+ print("Optimizer model is not loaded.")
74
+ response_data['optimization'] = "Error: Optimizer model is not loaded on server."
75
+
76
+ return jsonify(response_data)
77
+
78
+ except Exception as e:
79
+ print(f"--- ERROR during prediction: {e} ---")
80
+ return jsonify({'error': f'Prediction failed: {e}'}), 500
81
+
82
+ # --- 4. Run the Server ---
83
+ if __name__ == '__main__':
84
+ print("Starting Flask server on http://127.0.0.1:5000")
85
  app.run(debug=True, port=5000)