auto-code-optimizer / server.py
athv's picture
Update server.py
e1089e2 verified
Raw History Blame
3.3 kB
import sys
from flask import Flask, request, jsonify
from flask_cors import CORS
from transformers import pipeline, AutoTokenizer # <-- ADDED AutoTokenizer
# --- 1. Initialize Flask App ---
app = Flask(__name__)
CORS(app)
# --- 2. Load Your Models ---
print("--- Server is starting ---")
print(f"Python version: {sys.version}")
optimizer_pipeline = None
# --- Hugging Face Model Loading ---
try:
# This is our smart chat model
model_name = 'TinyLlama/TinyLlama-1.1B-Chat-v1.0'
print(f"Loading {model_name} model...")
hf_task = 'text-generation'
# --- THIS IS THE "STOP" TOKEN FIX ---
# 1. We load the tokenizer so we know its "stop" token
tokenizer = AutoTokenizer.from_pretrained(model_name)
# 2. We pass the model AND the tokenizer to the pipeline
optimizer_pipeline = pipeline(hf_task, model=model_name, tokenizer=tokenizer)
# --- END FIX ---
print("Hugging Face model loaded successfully.")
print("--- Server is ready. ---")
except Exception as e_hf:
print(f"--- CRITICAL ERROR loading Hugging Face model: {e_hf} ---")
print("--- Server will not work. ---")
# --- 3. 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
code_snippet = request.json['code']
print(f"Received prompt length: {len(code_snippet)} chars")
response_data = {}
try:
# --- Use Optimizer (Hugging Face) ---
if optimizer_pipeline:
print("Running Hugging Face model...")
# --- THIS IS THE TYPO FIX ---
# It is 'opt_result', not 'opt_.result'
opt_result = optimizer_pipeline(
code_snippet,
max_new_tokens=200,
eos_token_id=tokenizer.eos_token_id # <-- THIS TELLS IT TO STOP
)
# --- END TYPO FIX ---
full_response = opt_result[0]['generated_text']
# Clean up: We only want the part AFTER "Optimized Code:"
# We must clean the *original* prompt, not the *new* one.
if "<|assistant|>" in full_response:
clean_optimization = full_response.split("<|assistant|>")[-1].strip()
elif "Optimized Code:" in full_response:
clean_optimization = full_response.split("Optimized Code:")[-1].strip()
else:
clean_optimization = full_response
response_data['optimization'] = clean_optimization
print("Optimization generated successfully.")
else:
print("Optimizer model is not loaded.")
response_data['optimization'] = "Error: Optimizer model is not loaded on server."
return jsonify(response_data)
except Exception as e:
print(f"--- ERROR during prediction: {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)