Spaces:
Sleeping
Sleeping
File size: 2,229 Bytes
9181a5f 8a48afb 2744c71 9181a5f 2744c71 9181a5f 2744c71 9181a5f 2744c71 9181a5f 2744c71 8a48afb a36a3fc 2744c71 9181a5f 2744c71 9181a5f 2744c71 9181a5f 2744c71 9181a5f e852b8c 92e165d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import sys
import os # <-- ADDED THIS
import requests
from flask import Flask, request, jsonify
from flask_cors import CORS
# --- 1. Initialize Flask App ---
app = Flask(__name__)
CORS(app)
print("--- Gemini API Server is starting ---")
# --- 2. Create an API Endpoint ---
@app.route('/optimize', methods=['POST'])
def optimize_code():
print("\n--- Received a request ---")
if not request.json or 'code' not in request.json:
print("Request error: No 'code' key in JSON.")
return jsonify({'error': 'No code provided'}), 400
# This 'user_prompt' contains your full "Expert" prompt from VS Code
user_prompt = request.json['code']
print(f"Received prompt length: {len(user_prompt)} chars")
try:
# --- 3. Call the Gemini API ---
# --- THIS IS THE FIX ---
# It now reads the secret key you just saved
api_key = os.environ.get("GOOGLE_API_KEY")
if not api_key:
raise Exception("GOOGLE_API_KEY secret is not set.")
# --- END FIX ---
api_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={api_key}"
# Construct the payload for Gemini
payload = {
"contents": [{
"parts": [{ "text": user_prompt }]
}]
}
print("Sending request to Gemini API...")
# Make the API call
response = requests.post(api_url, json=payload, headers={'Content-Type': 'application/json'})
response.raise_for_status() # Raise an error if the request failed
result = response.json()
# Extract the optimized code from Gemini's response
optimized_code = result['candidates'][0]['content']['parts'][0]['text']
print("Optimization generated successfully.")
return jsonify({'optimization': optimized_code})
except Exception as e:
print(f"--- ERROR during Gemini API call: {e} ---")
return jsonify({'error': f'Prediction failed: {e}'}), 500
# --- 4. Run the Server ---
if __name__ == '__main__':
# Listen on 0.0.0.0 to allow external connections
app.run(host='0.0.0.0', port=7860) |