crying_cv / webcam_auto_inference.py
cho-sr's picture
Upload 100 files
9317120 verified
"""
SmolVLM Webcam Auto Inference (Fine-tuned)
3์ดˆ๋งˆ๋‹ค ์ž๋™์œผ๋กœ inference ์ˆ˜ํ–‰
Fine-tuned on Hair classification & description dataset
"""
import torch
from PIL import Image
from transformers import AutoProcessor, AutoModelForImageTextToText
from peft import PeftModel
import gradio as gr
import numpy as np
from datetime import datetime
import time
# =========================
# ์„ค์ •
# =========================
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
BASE_MODEL_ID = "HuggingFaceTB/SmolVLM-256M-Instruct"
FINETUNED_MODEL_PATH = "/root/crying_cv_vlm/checkpoint-105" # โœ… ์ตœ์ข… ํ•™์Šต๋œ ๋ชจ๋ธ (checkpoint-105)
INFERENCE_INTERVAL = 3 # 3์ดˆ ๊ฐ„๊ฒฉ
print(f"๐Ÿ”ง Device: {DEVICE}")
print(f"๐Ÿ“‚ Fine-tuned Model: {FINETUNED_MODEL_PATH}")
print("Loading model...")
# =========================
# ๋ชจ๋ธ ๋กœ๋“œ (Fine-tuned LoRA)
# =========================
from transformers import AutoModelForImageTextToText
from peft import PeftModel
print("1๏ธโƒฃ Loading base model...")
model = AutoModelForImageTextToText.from_pretrained(
BASE_MODEL_ID,
dtype=torch.bfloat16 if DEVICE == "cuda" else torch.float32,
device_map="auto",
attn_implementation="eager"
)
print("2๏ธโƒฃ Loading fine-tuned adapter...")
model = PeftModel.from_pretrained(
model,
FINETUNED_MODEL_PATH,
device_map="auto"
)
print("3๏ธโƒฃ Merging adapter...")
model = model.merge_and_unload()
model.eval()
print("4๏ธโƒฃ Loading processor...")
processor = AutoProcessor.from_pretrained(FINETUNED_MODEL_PATH)
print("โœ… Model loaded!")
if torch.cuda.is_available():
print(f"๐Ÿ’พ VRAM: {torch.cuda.memory_allocated(0) / 1024**3:.2f} GB")
def inference(image, question):
"""์ด๋ฏธ์ง€์™€ ์งˆ๋ฌธ์„ ๋ฐ›์•„ inference ์ˆ˜ํ–‰"""
if image is None:
return "โš ๏ธ ์›น์บ ์—์„œ ์ด๋ฏธ์ง€๋ฅผ ์บก์ฒ˜ํ•ด์ฃผ์„ธ์š”.", "๋Œ€๊ธฐ ์ค‘"
if not question or question.strip() == "":
question = "Describe this image in detail."
try:
# Convert to PIL Image
if isinstance(image, np.ndarray):
image = Image.fromarray(image).convert('RGB')
elif not isinstance(image, Image.Image):
return "โŒ ์ž˜๋ชป๋œ ์ด๋ฏธ์ง€ ํ˜•์‹", "์—๋Ÿฌ"
elif image.mode != 'RGB':
image = image.convert('RGB')
# Prepare messages
messages = [{
"role": "user",
"content": [{"type": "image"}, {"type": "text", "text": question}]
}]
# Process
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
inputs = processor(text=prompt, images=[image], return_tensors="pt").to(DEVICE)
# ์ž…๋ ฅ ๊ธธ์ด ์ €์žฅ
input_len = inputs["input_ids"].shape[-1]
# Generate
with torch.inference_mode():
generated_ids = model.generate(
**inputs,
max_new_tokens=100,
do_sample=True,
temperature=0.7,
top_p=0.9
)
# Decode (์ƒˆ๋กœ ์ƒ์„ฑ๋œ ํ† ํฐ๋งŒ)
generated_ids = generated_ids[0][input_len:]
response = processor.decode(generated_ids, skip_special_tokens=True).strip()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
status = f"โœ… {timestamp}"
return response if response else "(๋นˆ ์‘๋‹ต)", status
except Exception as e:
import traceback
error_msg = traceback.format_exc()
return f"โŒ ์—๋Ÿฌ: {str(e)}\n\n{error_msg}", "์—๋Ÿฌ ๋ฐœ์ƒ"
# =========================
# Gradio UI
# =========================
with gr.Blocks(title="SmolVLM Auto Inference") as demo:
gr.Markdown("""
# ๐ŸŽฅ SmolVLM ์›น์บ  ์ž๋™ ์ถ”๋ก  (Fine-tuned)
**3์ดˆ๋งˆ๋‹ค ์ž๋™์œผ๋กœ ์ถ”๋ก ์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค**
### ๋ชจ๋ธ ์ •๋ณด:
- **Base Model**: HuggingFaceTB/SmolVLM-256M-Instruct
- **Fine-tuned on**: Hair classification & description dataset
- **Training**: 5 epochs, Final loss: 1.1350
### ์‚ฌ์šฉ ๋ฐฉ๋ฒ•:
1. ์›น์บ  ํ—ˆ์šฉ ๋ฐ ์ด๋ฏธ์ง€ ์บก์ฒ˜
2. ์งˆ๋ฌธ ์ž…๋ ฅ
3. "๐Ÿš€ ์ž๋™ ์ถ”๋ก  ์‹œ์ž‘" ๋ฒ„ํŠผ ํด๋ฆญ
4. 3์ดˆ๋งˆ๋‹ค ์ž๋™์œผ๋กœ ์ถ”๋ก ๋ฉ๋‹ˆ๋‹ค
5. "โธ๏ธ ์ค‘์ง€" ๋ฒ„ํŠผ์œผ๋กœ ๋ฉˆ์ถœ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
""")
with gr.Row():
with gr.Column(scale=1):
# ์›น์บ  (streaming ํ™œ์„ฑํ™”)
webcam = gr.Image(
label="๐Ÿ“ท ์›น์บ ",
type="numpy",
sources=["webcam"],
streaming=True, # ์ŠคํŠธ๋ฆฌ๋ฐ ํ™œ์„ฑํ™”
height=400
)
# ์งˆ๋ฌธ ์ž…๋ ฅ
question = gr.Textbox(
label="๐Ÿ’ฌ ์งˆ๋ฌธ",
placeholder="์ด๋ฏธ์ง€์— ๋Œ€ํ•ด ๋ฌผ์–ด๋ณด๊ณ  ์‹ถ์€ ๊ฒƒ์„ ์ž…๋ ฅํ•˜์„ธ์š”",
value="Classify the hair length in this image. Possible values: short, mid, long. Output only one word.",
lines=3
)
with gr.Row():
start_btn = gr.Button("๐Ÿš€ ์ž๋™ ์ถ”๋ก  ์‹œ์ž‘", variant="primary", scale=2)
stop_btn = gr.Button("โธ๏ธ ์ค‘์ง€", variant="stop", scale=1)
with gr.Column(scale=1):
# ์ถœ๋ ฅ
output = gr.Textbox(
label="๐Ÿค– ์‘๋‹ต",
lines=15,
max_lines=20
)
# ์ƒํƒœ
status = gr.Textbox(
label="๐Ÿ“Š ์ƒํƒœ",
value="๋Œ€๊ธฐ ์ค‘",
lines=1
)
# ์ž๋™ ์ถ”๋ก  ์ƒํƒœ
auto_status = gr.Textbox(
label="๐Ÿ”„ ์ž๋™ ์ถ”๋ก  ์ƒํƒœ",
value="๋ฉˆ์ถค",
lines=1
)
# ์˜ˆ์‹œ ์งˆ๋ฌธ
gr.Markdown("### ๐Ÿ’ก ์˜ˆ์‹œ ์งˆ๋ฌธ:")
gr.Examples(
examples=[
["Classify the hair length in this image. Possible values: short, mid, long. Output only one word."],
["Describe the person's hair style, color, and texture in detail."],
["What is the hair length? Answer in one word: short, mid, or long."],
["Describe what you see in this image."],
["์ด ์‚ฌ๋žŒ์˜ ๋จธ๋ฆฌ ๊ธธ์ด๋ฅผ ๋ถ„๋ฅ˜ํ•˜์„ธ์š”. ๊ฐ€๋Šฅํ•œ ๊ฐ’: short, mid, long"],
],
inputs=[question],
)
# ์ž๋™ ์ถ”๋ก  ์ œ์–ด
is_auto_running = gr.State(value=False)
last_inference_time = gr.State(value=0)
def start_auto_inference():
"""์ž๋™ ์ถ”๋ก  ์‹œ์ž‘"""
# ํ˜„์žฌ ์‹œ๊ฐ„์œผ๋กœ ์„ค์ •ํ•˜์—ฌ ์ฆ‰์‹œ ์ฒซ ์ถ”๋ก  ์‹œ์ž‘
return True, "โ–ถ๏ธ ์‹คํ–‰ ์ค‘ (3์ดˆ ๊ฐ„๊ฒฉ)", gr.Timer(value=0.5, active=True), time.time() - INFERENCE_INTERVAL
def stop_auto_inference():
"""์ž๋™ ์ถ”๋ก  ์ค‘์ง€"""
return False, "โธ๏ธ ๋ฉˆ์ถค", gr.Timer(value=0.5, active=False)
def auto_inference_loop(image, question_text, is_running, last_time):
"""์ž๋™ ์ถ”๋ก  ๋ฃจํ”„ (3์ดˆ๋งˆ๋‹ค ์‹คํ–‰)"""
if not is_running:
return gr.update(), gr.update(), last_time
current_time = time.time()
# ์ด๋ฏธ์ง€ ์—†์œผ๋ฉด ๊ฒฝ๊ณ  ๋ฉ”์‹œ์ง€
if image is None:
return gr.update(), "โš ๏ธ ์›น์บ  ์ด๋ฏธ์ง€๋ฅผ ์บก์ฒ˜ํ•ด์ฃผ์„ธ์š”", last_time
# 3์ดˆ ๊ฒฝ๊ณผ ํ™•์ธ
if current_time - last_time >= INFERENCE_INTERVAL:
result, status_msg = inference(image, question_text)
return result, status_msg, current_time
else:
# ๋Œ€๊ธฐ ์ค‘ ๋‚จ์€ ์‹œ๊ฐ„ ํ‘œ์‹œ
remaining = INFERENCE_INTERVAL - (current_time - last_time)
return gr.update(), f"โฑ๏ธ ๋‹ค์Œ ์ถ”๋ก ๊นŒ์ง€ {remaining:.1f}์ดˆ", last_time
# ์ž๋™ ์ถ”๋ก  ํƒ€์ด๋จธ
timer = gr.Timer(value=0.5, active=False)
# ์‹œ์ž‘ ๋ฒ„ํŠผ
start_btn.click(
fn=start_auto_inference,
inputs=[],
outputs=[is_auto_running, auto_status, timer, last_inference_time]
)
# ์ค‘์ง€ ๋ฒ„ํŠผ
stop_btn.click(
fn=stop_auto_inference,
inputs=[],
outputs=[is_auto_running, auto_status, timer]
)
# ํƒ€์ด๋จธ ํ‹ฑ
timer.tick(
fn=auto_inference_loop,
inputs=[webcam, question, is_auto_running, last_inference_time],
outputs=[output, status, last_inference_time]
)
if __name__ == "__main__":
print("\n" + "="*70)
print("๐Ÿš€ Launching at http://0.0.0.0:7860")
print("="*70 + "\n")
demo.launch(
server_name="0.0.0.0",
server_port=8085,
share=False,
show_error=True
)