Spaces:
Sleeping
Sleeping
Kelvin Tepes commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,70 +1,61 @@
|
|
| 1 |
from flask import Flask, request, jsonify
|
| 2 |
from flask_cors import CORS
|
| 3 |
import os
|
| 4 |
-
import
|
| 5 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 6 |
|
| 7 |
app = Flask(__name__)
|
| 8 |
-
CORS(app)
|
| 9 |
|
| 10 |
-
|
| 11 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
# 1. Load the tokenizer matching your exact model structure
|
| 16 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_TOKEN)
|
| 17 |
-
|
| 18 |
-
# 2. Configure 4-bit loading directly inside your Space container memory
|
| 19 |
-
bnb_config = BitsAndBytesConfig(
|
| 20 |
-
load_in_4bit=True,
|
| 21 |
-
bnb_4bit_quant_type="nf4",
|
| 22 |
-
bnb_4bit_compute_dtype=torch.float16
|
| 23 |
-
)
|
| 24 |
-
|
| 25 |
-
# 3. Pull weights directly into local cache space
|
| 26 |
-
try:
|
| 27 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 28 |
-
MODEL_NAME,
|
| 29 |
-
quantization_config=bnb_config,
|
| 30 |
-
device_map="auto",
|
| 31 |
-
token=HF_TOKEN
|
| 32 |
-
)
|
| 33 |
-
print("Krypton-1 Core Engine Fully Loaded in Space Memory.")
|
| 34 |
-
except Exception as e:
|
| 35 |
-
print(f"Boot Failure Error: {str(e)}")
|
| 36 |
-
model = None
|
| 37 |
|
| 38 |
@app.route("/", methods=["GET"])
|
| 39 |
def home():
|
| 40 |
-
return "Krypton-1
|
| 41 |
|
| 42 |
@app.route("/api/chat", methods=["POST"])
|
| 43 |
def chat():
|
| 44 |
-
if model is None:
|
| 45 |
-
return jsonify({"reply": "SYS_ERR: Engine failed to cache local weights. Check container storage logs."})
|
| 46 |
-
|
| 47 |
try:
|
| 48 |
data = request.json
|
| 49 |
user_prompt = data.get("prompt", "")
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
# Generate raw response tokens straight from your loaded weights
|
| 56 |
-
outputs = model.generate(inputs, max_new_tokens=250, temperature=0.7, do_sample=True)
|
| 57 |
|
| 58 |
-
#
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
except Exception as e:
|
| 67 |
-
return jsonify({"reply": f"
|
| 68 |
|
| 69 |
if __name__ == "__main__":
|
| 70 |
app.run(host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
from flask import Flask, request, jsonify
|
| 2 |
from flask_cors import CORS
|
| 3 |
import os
|
| 4 |
+
import requests
|
|
|
|
| 5 |
|
| 6 |
app = Flask(__name__)
|
| 7 |
+
CORS(app) # Keeps your Acode terminal connected securely!
|
| 8 |
|
| 9 |
+
# Pulls your hidden WRITE token from Space secrets
|
| 10 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 11 |
+
MODEL_REPO = "unsloth/mistral-7b-instruct-v0.3-bnb-4bit"
|
| 12 |
+
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_REPO}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
@app.route("/", methods=["GET"])
|
| 15 |
def home():
|
| 16 |
+
return "Krypton-1 Core Unsloth Node Active."
|
| 17 |
|
| 18 |
@app.route("/api/chat", methods=["POST"])
|
| 19 |
def chat():
|
|
|
|
|
|
|
|
|
|
| 20 |
try:
|
| 21 |
data = request.json
|
| 22 |
user_prompt = data.get("prompt", "")
|
| 23 |
|
| 24 |
+
headers = {
|
| 25 |
+
"Authorization": f"Bearer {HF_TOKEN}",
|
| 26 |
+
"Content-Type": "application/json"
|
| 27 |
+
}
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
# Structure the payload exactly how the serverless API wants it
|
| 30 |
+
payload = {
|
| 31 |
+
"inputs": f"<s>[INST] {user_prompt} [/INST]",
|
| 32 |
+
"parameters": {
|
| 33 |
+
"max_new_tokens": 250,
|
| 34 |
+
"temperature": 0.7,
|
| 35 |
+
"return_full_text": False
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
|
| 39 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
| 40 |
+
res_data = response.json()
|
| 41 |
|
| 42 |
+
# Check if the API tells us the model is still loading weights on their servers
|
| 43 |
+
if isinstance(res_data, dict) and "error" in res_data:
|
| 44 |
+
err_msg = res_data.get("error", "")
|
| 45 |
+
if "loading" in err_msg.lower():
|
| 46 |
+
est_time = round(res_data.get('estimated_time', 20))
|
| 47 |
+
return jsonify({"reply": f"SYS_BOOT: Krypton-1 is loading on Hugging Face clusters. Activation wait time: {est_time}s. Try hitting RUN again in a moment!"})
|
| 48 |
+
return jsonify({"reply": f"SYS_ALERT: API Error. Details: {err_msg}"})
|
| 49 |
+
|
| 50 |
+
# Extract the text cleanly
|
| 51 |
+
if isinstance(res_data, list) and len(res_data) > 0:
|
| 52 |
+
reply = res_data[0].get("generated_text", "Data packet empty.")
|
| 53 |
+
return jsonify({"reply": reply})
|
| 54 |
+
else:
|
| 55 |
+
return jsonify({"reply": f"SYS_ALERT: Unexpected API data layout format. Received: {str(res_data)}"})
|
| 56 |
|
| 57 |
except Exception as e:
|
| 58 |
+
return jsonify({"reply": f"SYS_ERR: Proxy pipeline broken. {str(e)}"})
|
| 59 |
|
| 60 |
if __name__ == "__main__":
|
| 61 |
app.run(host="0.0.0.0", port=7860)
|