File size: 3,295 Bytes
9181a5f
 
 
e1089e2
9181a5f
 
 
 
 
 
 
 
 
 
 
 
 
0582940
73ff042
9181a5f
 
0582940
9181a5f
e1089e2
 
0582940
e1089e2
 
0582940
 
9181a5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1089e2
 
3c43ccb
0582940
 
e1089e2
0582940
e1089e2
9181a5f
 
 
23b1e25
e1089e2
 
 
 
 
9181a5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0582940
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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)