athv commited on
Commit
2744c71
·
verified ·
1 Parent(s): e852b8c

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +33 -58
server.py CHANGED
@@ -1,40 +1,16 @@
1
  import sys
 
 
2
  from flask import Flask, request, jsonify
3
  from flask_cors import CORS
4
- from transformers import pipeline, AutoTokenizer # <-- MUST HAVE THIS
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 our smart chat model
19
- model_name = 'TinyLlama/TinyLlama-1.1B-Chat-v1.0'
20
-
21
- print(f"Loading {model_name} model...")
22
- hf_task = 'text-generation'
23
-
24
- # --- MUST HAVE THIS TOKENIZER FIX ---
25
- tokenizer = AutoTokenizer.from_pretrained(model_name)
26
- optimizer_pipeline = pipeline(hf_task, model=model_name, tokenizer=tokenizer)
27
- # --- END FIX ---
28
-
29
- print("Hugging Face model loaded successfully.")
30
- print("--- Server is ready. ---")
31
-
32
- except Exception as e_hf:
33
- print(f"--- CRITICAL ERROR loading Hugging Face model: {e_hf} ---")
34
- print("--- Server will not work. ---")
35
-
36
-
37
- # --- 3. Create an API Endpoint ---
38
  @app.route('/optimize', methods=['POST'])
39
  def optimize_code():
40
  print("\n--- Received a request ---")
@@ -43,42 +19,41 @@ def optimize_code():
43
  print("Request error: No 'code' key in JSON.")
44
  return jsonify({'error': 'No code provided'}), 400
45
 
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 with the "stop" token
57
- opt_result = optimizer_pipeline(
58
- code_snippet,
59
- max_new_tokens=200,
60
- eos_token_id=tokenizer.eos_token_id # <-- MUST HAVE THIS
61
- )
62
-
63
- full_response = opt_result[0]['generated_text']
64
-
65
- # Clean up: We only want the part AFTER "Optimized Code:"
66
- if "Optimized Code:" in full_response:
67
- clean_optimization = full_response.split("Optimized Code:")[-1].strip()
68
- else:
69
- clean_optimization = full_response
 
 
70
 
71
- response_data['optimization'] = clean_optimization
72
- print("Optimization generated successfully.")
73
-
74
- else:
75
- print("Optimizer model is not loaded.")
76
- response_data['optimization'] = "Error: Optimizer model is not loaded on server."
77
 
78
- return jsonify(response_data)
79
 
80
  except Exception as e:
81
- print(f"--- ERROR during prediction: {e} ---")
82
  return jsonify({'error': f'Prediction failed: {e}'}), 500
83
 
84
  # --- 4. Run the Server ---
 
1
  import sys
2
+ import os
3
+ import requests
4
  from flask import Flask, request, jsonify
5
  from flask_cors import CORS
 
6
 
7
  # --- 1. Initialize Flask App ---
8
  app = Flask(__name__)
9
  CORS(app)
10
 
11
+ print("--- Gemini API Server is starting ---")
 
 
12
 
13
+ # --- 2. Create an API Endpoint ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  @app.route('/optimize', methods=['POST'])
15
  def optimize_code():
16
  print("\n--- Received a request ---")
 
19
  print("Request error: No 'code' key in JSON.")
20
  return jsonify({'error': 'No code provided'}), 400
21
 
22
+ # This 'user_prompt' contains your full "Expert" prompt from VS Code
23
+ user_prompt = request.json['code']
24
+ print(f"Received prompt length: {len(user_prompt)} chars")
 
25
 
26
  try:
27
+ # --- 3. Call the Gemini API ---
28
+
29
+ # We leave the API key blank. Canvas will provide it.
30
+ api_key = ""
31
+ api_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-09-2025:generateContent?key={api_key}"
32
+
33
+ # Construct the payload for Gemini
34
+ payload = {
35
+ "contents": [{
36
+ "parts": [{ "text": user_prompt }]
37
+ }]
38
+ }
39
+
40
+ print("Sending request to Gemini API...")
41
+
42
+ # Make the API call
43
+ response = requests.post(api_url, json=payload, headers={'Content-Type': 'application/json'})
44
+ response.raise_for_status() # Raise an error if the request failed
45
+
46
+ result = response.json()
47
 
48
+ # Extract the optimized code from Gemini's response
49
+ optimized_code = result['candidates'][0]['content']['parts'][0]['text']
50
+
51
+ print("Optimization generated successfully.")
 
 
52
 
53
+ return jsonify({'optimization': optimized_code})
54
 
55
  except Exception as e:
56
+ print(f"--- ERROR during Gemini API call: {e} ---")
57
  return jsonify({'error': f'Prediction failed: {e}'}), 500
58
 
59
  # --- 4. Run the Server ---