Spaces:
Runtime error
Runtime error
Rename app.py to main.py
Browse files- app.py → main.py +14 -49
app.py → main.py
RENAMED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
import os
|
| 2 |
import torch
|
| 3 |
-
from threading import Thread
|
| 4 |
from PIL import Image
|
| 5 |
import numpy as np
|
| 6 |
|
|
@@ -11,18 +10,16 @@ import gradio as gr
|
|
| 11 |
from transformers import (
|
| 12 |
AutoModelForCausalLM,
|
| 13 |
AutoTokenizer,
|
| 14 |
-
TextIteratorStreamer,
|
| 15 |
AutoProcessor,
|
| 16 |
)
|
| 17 |
|
| 18 |
-
# Force CPU
|
| 19 |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 20 |
torch.cuda.is_available = lambda: False
|
| 21 |
device = "cpu"
|
| 22 |
print("Running on CPU ✅")
|
| 23 |
|
| 24 |
-
# ---------------- LOAD
|
| 25 |
-
|
| 26 |
MODEL_ID = "microsoft/Phi-3.5-mini-instruct"
|
| 27 |
|
| 28 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
|
@@ -33,8 +30,7 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
| 33 |
low_cpu_mem_usage=True
|
| 34 |
).eval()
|
| 35 |
|
| 36 |
-
# ---------------- LOAD VISION MODEL
|
| 37 |
-
|
| 38 |
models = {}
|
| 39 |
processors = {}
|
| 40 |
|
|
@@ -46,48 +42,32 @@ try:
|
|
| 46 |
torch_dtype=torch.float32,
|
| 47 |
device_map="cpu",
|
| 48 |
low_cpu_mem_usage=True,
|
| 49 |
-
attn_implementation="eager"
|
| 50 |
).eval()
|
| 51 |
|
| 52 |
processors[VISION_ID] = AutoProcessor.from_pretrained(
|
| 53 |
VISION_ID,
|
| 54 |
trust_remote_code=True
|
| 55 |
)
|
| 56 |
-
|
| 57 |
print("Vision model loaded ✅")
|
| 58 |
except Exception as e:
|
| 59 |
print("Vision model failed to load:", e)
|
| 60 |
|
| 61 |
-
# ---------------- CHAT FUNCTION
|
| 62 |
-
|
| 63 |
def chat_simple(message, history):
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
conversation = [{"role": "system", "content": system_prompt}]
|
| 67 |
for user, assistant in history:
|
| 68 |
conversation.append({"role": "user", "content": user})
|
| 69 |
conversation.append({"role": "assistant", "content": assistant})
|
| 70 |
conversation.append({"role": "user", "content": message})
|
| 71 |
|
| 72 |
-
input_ids = tokenizer.apply_chat_template(
|
| 73 |
-
|
| 74 |
-
add_generation_prompt=True,
|
| 75 |
-
return_tensors="pt"
|
| 76 |
-
).to(device)
|
| 77 |
-
|
| 78 |
-
output = model.generate(
|
| 79 |
-
input_ids,
|
| 80 |
-
max_new_tokens=256,
|
| 81 |
-
temperature=0.7,
|
| 82 |
-
top_p=0.9,
|
| 83 |
-
do_sample=True
|
| 84 |
-
)
|
| 85 |
|
| 86 |
reply = tokenizer.decode(output[0][input_ids.shape[1]:], skip_special_tokens=True)
|
| 87 |
return reply
|
| 88 |
|
| 89 |
# ---------------- VISION FUNCTION ----------------
|
| 90 |
-
|
| 91 |
def run_vision(image, text_input, model_id):
|
| 92 |
if model_id not in models:
|
| 93 |
return "⚠️ Vision model not loaded."
|
|
@@ -103,34 +83,20 @@ def run_vision(image, text_input, model_id):
|
|
| 103 |
template = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 104 |
inputs = processor(template, [img], return_tensors="pt")
|
| 105 |
|
| 106 |
-
output = model_vision.generate(
|
| 107 |
-
**inputs,
|
| 108 |
-
max_new_tokens=400,
|
| 109 |
-
do_sample=False,
|
| 110 |
-
)
|
| 111 |
-
|
| 112 |
output = output[:, inputs["input_ids"].shape[1]:]
|
| 113 |
-
|
| 114 |
-
return text
|
| 115 |
-
|
| 116 |
-
# ---------------- FASTAPI BACKEND API ----------------
|
| 117 |
|
|
|
|
| 118 |
api = FastAPI()
|
| 119 |
|
| 120 |
@api.get("/health")
|
| 121 |
def health():
|
| 122 |
-
return {
|
| 123 |
-
"status": "ok",
|
| 124 |
-
"device": device,
|
| 125 |
-
"chat_model": MODEL_ID,
|
| 126 |
-
"vision_loaded": len(models) > 0
|
| 127 |
-
}
|
| 128 |
|
| 129 |
@api.post("/api/chat")
|
| 130 |
async def api_chat(message: str = Form(...)):
|
| 131 |
-
conversation = [{"role": "
|
| 132 |
-
{"role": "user", "content": message}]
|
| 133 |
-
|
| 134 |
input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
|
| 135 |
output = model.generate(input_ids, max_new_tokens=256)
|
| 136 |
reply = tokenizer.decode(output[0][input_ids.shape[1]:], skip_special_tokens=True)
|
|
@@ -142,7 +108,6 @@ async def api_vision(image: UploadFile = File(...), text_input: str = Form("Desc
|
|
| 142 |
return {"response": run_vision(np.array(img), text_input, model_id)}
|
| 143 |
|
| 144 |
# ---------------- GRADIO UI ----------------
|
| 145 |
-
|
| 146 |
def create_ui():
|
| 147 |
with gr.Blocks() as demo:
|
| 148 |
with gr.Tab("Chat"):
|
|
@@ -151,7 +116,7 @@ def create_ui():
|
|
| 151 |
with gr.Tab("Vision"):
|
| 152 |
img = gr.Image()
|
| 153 |
txt = gr.Textbox("What's in this image?")
|
| 154 |
-
model_sel = gr.Dropdown(choices=list(models.keys())
|
| 155 |
out = gr.Textbox()
|
| 156 |
gr.Button("Analyze").click(run_vision, [img, txt, model_sel], out)
|
| 157 |
|
|
|
|
| 1 |
import os
|
| 2 |
import torch
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
import numpy as np
|
| 5 |
|
|
|
|
| 10 |
from transformers import (
|
| 11 |
AutoModelForCausalLM,
|
| 12 |
AutoTokenizer,
|
|
|
|
| 13 |
AutoProcessor,
|
| 14 |
)
|
| 15 |
|
| 16 |
+
# Force CPU Only
|
| 17 |
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
|
| 18 |
torch.cuda.is_available = lambda: False
|
| 19 |
device = "cpu"
|
| 20 |
print("Running on CPU ✅")
|
| 21 |
|
| 22 |
+
# ---------------- LOAD CHAT MODEL ----------------
|
|
|
|
| 23 |
MODEL_ID = "microsoft/Phi-3.5-mini-instruct"
|
| 24 |
|
| 25 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
|
|
|
| 30 |
low_cpu_mem_usage=True
|
| 31 |
).eval()
|
| 32 |
|
| 33 |
+
# ---------------- LOAD VISION MODEL ----------------
|
|
|
|
| 34 |
models = {}
|
| 35 |
processors = {}
|
| 36 |
|
|
|
|
| 42 |
torch_dtype=torch.float32,
|
| 43 |
device_map="cpu",
|
| 44 |
low_cpu_mem_usage=True,
|
| 45 |
+
attn_implementation="eager"
|
| 46 |
).eval()
|
| 47 |
|
| 48 |
processors[VISION_ID] = AutoProcessor.from_pretrained(
|
| 49 |
VISION_ID,
|
| 50 |
trust_remote_code=True
|
| 51 |
)
|
|
|
|
| 52 |
print("Vision model loaded ✅")
|
| 53 |
except Exception as e:
|
| 54 |
print("Vision model failed to load:", e)
|
| 55 |
|
| 56 |
+
# ---------------- CHAT FUNCTION ----------------
|
|
|
|
| 57 |
def chat_simple(message, history):
|
| 58 |
+
conversation = [{"role": "system", "content": "You are a helpful assistant."}]
|
|
|
|
|
|
|
| 59 |
for user, assistant in history:
|
| 60 |
conversation.append({"role": "user", "content": user})
|
| 61 |
conversation.append({"role": "assistant", "content": assistant})
|
| 62 |
conversation.append({"role": "user", "content": message})
|
| 63 |
|
| 64 |
+
input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
|
| 65 |
+
output = model.generate(input_ids, max_new_tokens=256)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
reply = tokenizer.decode(output[0][input_ids.shape[1]:], skip_special_tokens=True)
|
| 68 |
return reply
|
| 69 |
|
| 70 |
# ---------------- VISION FUNCTION ----------------
|
|
|
|
| 71 |
def run_vision(image, text_input, model_id):
|
| 72 |
if model_id not in models:
|
| 73 |
return "⚠️ Vision model not loaded."
|
|
|
|
| 83 |
template = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 84 |
inputs = processor(template, [img], return_tensors="pt")
|
| 85 |
|
| 86 |
+
output = model_vision.generate(**inputs, max_new_tokens=400, do_sample=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
output = output[:, inputs["input_ids"].shape[1]:]
|
| 88 |
+
return processor.batch_decode(output, skip_special_tokens=True)[0]
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
# ---------------- FASTAPI BACKEND ----------------
|
| 91 |
api = FastAPI()
|
| 92 |
|
| 93 |
@api.get("/health")
|
| 94 |
def health():
|
| 95 |
+
return {"status": "ok", "device": device, "vision_loaded": len(models) > 0}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
@api.post("/api/chat")
|
| 98 |
async def api_chat(message: str = Form(...)):
|
| 99 |
+
conversation = [{"role": "user", "content": message}]
|
|
|
|
|
|
|
| 100 |
input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
|
| 101 |
output = model.generate(input_ids, max_new_tokens=256)
|
| 102 |
reply = tokenizer.decode(output[0][input_ids.shape[1]:], skip_special_tokens=True)
|
|
|
|
| 108 |
return {"response": run_vision(np.array(img), text_input, model_id)}
|
| 109 |
|
| 110 |
# ---------------- GRADIO UI ----------------
|
|
|
|
| 111 |
def create_ui():
|
| 112 |
with gr.Blocks() as demo:
|
| 113 |
with gr.Tab("Chat"):
|
|
|
|
| 116 |
with gr.Tab("Vision"):
|
| 117 |
img = gr.Image()
|
| 118 |
txt = gr.Textbox("What's in this image?")
|
| 119 |
+
model_sel = gr.Dropdown(choices=list(models.keys()))
|
| 120 |
out = gr.Textbox()
|
| 121 |
gr.Button("Analyze").click(run_vision, [img, txt, model_sel], out)
|
| 122 |
|