Shahriar-jaman commited on
Commit
035e7b2
·
verified ·
1 Parent(s): bbfe653

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -40
app.py CHANGED
@@ -1,47 +1,78 @@
 
1
  import torch
 
2
  from PIL import Image
3
- from transformers import AutoProcessor, AutoModelForVision2Seq
4
- import gradio as gr
5
- import os
6
-
7
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
8
-
9
- token = os.environ.get("HF_TOKEN")
10
-
11
- processor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM-Instruct", token=token)
12
- model = AutoModelForVision2Seq.from_pretrained(
13
- "HuggingFaceTB/SmolVLM-Instruct",
14
- torch_dtype=torch.bfloat16 if DEVICE == "cuda" else torch.float32,
15
- _attn_implementation="flash_attention_2" if DEVICE == "cuda" else "eager",
16
- token=token
17
- ).to(DEVICE)
18
-
19
- def describe_image(image):
20
- messages = [
21
- {
22
- "role": "user",
23
- "content": [
24
- {"type": "image"},
25
- {"type": "text", "text": "Describe this image in detail."}
26
- ]
27
- },
28
- ]
29
 
30
- prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
31
- inputs = processor(text=prompt, images=[image], return_tensors="pt").to(DEVICE)
32
 
33
- with torch.no_grad():
34
- generated_ids = model.generate(**inputs, max_new_tokens=500)
 
 
35
 
36
- result = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
37
- return result
38
 
39
- demo = gr.Interface(
40
- fn=describe_image,
41
- inputs=gr.Image(type="pil", label="Upload an Image"),
42
- outputs="text",
43
- title="VISIONSAGE",
44
- description="Upload an image and get a detailed description."
45
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- demo.launch()
 
 
 
 
 
 
 
1
+ import os
2
  import torch
3
+ from transformers import AutoModelForCausalLM, AutoProcessor
4
  from PIL import Image
5
+ import numpy as np
6
+ from fastapi import FastAPI, UploadFile, File
7
+ from typing import List
8
+ import io
9
+ import uvicorn
10
+ from pyngrok import ngrok
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # Initialize FastAPI app
13
+ app = FastAPI()
14
 
15
+ # Load SmolVLM-Instruct model and processor
16
+ model_id = "HuggingFaceTB/SmolVLM-Instruct"
17
+ processor = AutoProcessor.from_pretrained(model_id, token=os.environ.get("HF_TOKEN"))
18
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16).to("cuda")
19
 
20
+ # Harmful objects list for detection
21
+ harmful_objects = ["knife", "gun", "weapon", "blood", "syringe"]
22
 
23
+ @app.post("/predict")
24
+ async def predict(files: List[UploadFile] = File(...)):
25
+ results = []
26
+ image_embeddings = []
27
+
28
+ for file in files:
29
+ # Read image
30
+ image_data = await file.read()
31
+ image = Image.open(io.BytesIO(image_data)).convert("RGB")
32
+
33
+ # Generate description
34
+ inputs = processor(text="Describe the image in detail.", images=image, return_tensors="pt").to("cuda")
35
+ outputs = model.generate(**inputs, max_length=100)
36
+ description = processor.decode(outputs[0], skip_special_tokens=True).replace("Describe the image in detail.", "").strip()
37
+
38
+ # Extract signs/number plates (OCR)
39
+ inputs_ocr = processor(text="Extract all text visible in the image.", images=image, return_tensors="pt").to("cuda")
40
+ ocr_outputs = model.generate(**inputs_ocr, max_length=100)
41
+ signs_text = processor.decode(ocr_outputs[0], skip_special_tokens=True).replace("Extract all text visible in the image.", "").strip()
42
+
43
+ # Detect harmful objects/blood
44
+ inputs_detect = processor(text="List all objects in the image.", images=image, return_tensors="pt").to("cuda")
45
+ detect_outputs = model.generate(**inputs_detect, max_length=100)
46
+ detected_objects = processor.decode(detect_outputs[0], skip_special_tokens=True).lower()
47
+ harmful_detected = any(obj in detected_objects for obj in harmful_objects) and "Detected" or "None detected"
48
+
49
+ # Get image embedding for similarity
50
+ inputs_emb = processor(images=image, return_tensors="pt").to("cuda")
51
+ with torch.no_grad():
52
+ emb = model.vision_tower(inputs_emb["pixel_values"]).last_hidden_state.mean(dim=1).cpu().numpy()
53
+ image_embeddings.append(emb)
54
+
55
+ results.append({
56
+ "description": description if description else "No description generated.",
57
+ "signs": signs_text if signs_text else "None detected",
58
+ "harmful": harmful_detected
59
+ })
60
+
61
+ # Compute similarity scores (cosine similarity to first image)
62
+ if len(image_embeddings) > 1:
63
+ base_embedding = image_embeddings[0]
64
+ for i in range(1, len(image_embeddings)):
65
+ sim = np.dot(base_embedding, image_embeddings[i].T) / (
66
+ np.linalg.norm(base_embedding) * np.linalg.norm(image_embeddings[i])
67
+ )
68
+ results[i]["similarity"] = float(sim[0][0])
69
+
70
+ return results
71
 
72
+ if __name__ == "__main__":
73
+ # Start ngrok tunnel
74
+ public_url = ngrok.connect(8000).public_url
75
+ print(f"Public URL: {public_url}")
76
+
77
+ # Run FastAPI server
78
+ uvicorn.run(app, host="0.0.0.0", port=8000)