Spaces:
Sleeping
Sleeping
Update server.py
Browse files
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 |
-
|
| 11 |
-
print("--- Server is starting ---")
|
| 12 |
-
print(f"Python version: {sys.version}")
|
| 13 |
|
| 14 |
-
|
| 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 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
response_data = {}
|
| 50 |
|
| 51 |
try:
|
| 52 |
-
# ---
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
print("Optimizer model is not loaded.")
|
| 76 |
-
response_data['optimization'] = "Error: Optimizer model is not loaded on server."
|
| 77 |
|
| 78 |
-
return jsonify(
|
| 79 |
|
| 80 |
except Exception as e:
|
| 81 |
-
print(f"--- ERROR during
|
| 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 ---
|