Itanutiwari527 commited on
Commit
981c23a
·
verified ·
1 Parent(s): c6d9ec5

Uploading app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -0
app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ import numpy as np
4
+ import pandas as pd
5
+ from PIL import Image, ImageDraw
6
+ from transformers import AutoProcessor, AutoModelForCausalLM
7
+
8
+ # Device settings
9
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
10
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
11
+
12
+ # Load model with caching
13
+ @st.cache_resource
14
+ def load_model():
15
+ CHECKPOINT = "microsoft/Florence-2-base-ft"
16
+ model = AutoModelForCausalLM.from_pretrained(CHECKPOINT, trust_remote_code=True).to(device, dtype=torch_dtype)
17
+ processor = AutoProcessor.from_pretrained(CHECKPOINT, trust_remote_code=True)
18
+ return model, processor
19
+
20
+ # Load the model and processor
21
+ try:
22
+ model, processor = load_model()
23
+ except Exception as e:
24
+ st.error(f"Model loading failed: {e}")
25
+ st.stop()
26
+
27
+ # UI title
28
+ st.title("Florence-2 Multi-Modal Model Playground")
29
+
30
+ # Task selector
31
+ task = st.selectbox("Select Task", ["Object Detection (OD)", "Phrase Grounding (PG)", "Image Captioning (IC)"])
32
+
33
+ # Phrase input for PG
34
+ phrase = ""
35
+ if task == "Phrase Grounding (PG)":
36
+ phrase = st.text_input("Enter phrase for grounding (e.g., 'A red car')", "")
37
+
38
+ # Image uploader
39
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
40
+
41
+ # If file uploaded
42
+ if uploaded_file:
43
+ try:
44
+ image = Image.open(uploaded_file).convert("RGB")
45
+ except Exception as e:
46
+ st.error(f"Error loading image: {e}")
47
+ st.stop()
48
+
49
+ st.image(image, caption="Uploaded Image", use_container_width=True)
50
+
51
+ # Task-specific prompt
52
+ if task == "Object Detection (OD)":
53
+ task_prompt = "<OD>"
54
+ elif task == "Phrase Grounding (PG)":
55
+ task_prompt = "<CAPTION_TO_PHRASE_GROUNDING>"
56
+ else:
57
+ task_prompt = "<CAPTION>"
58
+
59
+ # Preprocess inputs
60
+ try:
61
+ inputs = processor(text=task_prompt + phrase, images=image, return_tensors="pt").to(device, torch_dtype)
62
+ except Exception as e:
63
+ st.error(f"Error during preprocessing: {e}")
64
+ st.stop()
65
+
66
+ # Generate output
67
+ with torch.no_grad():
68
+ try:
69
+ generated_ids = model.generate(
70
+ input_ids=inputs["input_ids"],
71
+ pixel_values=inputs["pixel_values"],
72
+ max_new_tokens=512,
73
+ num_beams=3,
74
+ do_sample=False
75
+ )
76
+ except Exception as e:
77
+ st.error(f"Error during generation: {e}")
78
+ st.stop()
79
+
80
+ # Decode and post-process
81
+ try:
82
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
83
+ parsed_answer = processor.post_process_generation(
84
+ generated_text,
85
+ task=task_prompt,
86
+ image_size=(image.width, image.height)
87
+ )
88
+ except Exception as e:
89
+ st.error(f"Post-processing failed: {e}")
90
+ st.stop()
91
+
92
+ # Display results
93
+ if task in ["Object Detection (OD)", "Phrase Grounding (PG)"]:
94
+ key = "<OD>" if task == "Object Detection (OD)" else "<CAPTION_TO_PHRASE_GROUNDING>"
95
+ detections = parsed_answer.get(key, {"bboxes": [], "labels": []})
96
+ bboxes = detections.get("bboxes", [])
97
+ labels = detections.get("labels", [])
98
+
99
+ draw = ImageDraw.Draw(image)
100
+ data = []
101
+
102
+ for bbox, label in zip(bboxes, labels):
103
+ x_min, y_min, x_max, y_max = map(int, bbox)
104
+ draw.rectangle([x_min, y_min, x_max, y_max], outline="red", width=3)
105
+ draw.text((x_min, max(0, y_min - 10)), label, fill="red")
106
+ data.append([x_min, y_min, x_max - x_min, y_max - y_min, label])
107
+
108
+ st.image(image, caption="Detected Objects", use_container_width=True)
109
+ df = pd.DataFrame(data, columns=["x", "y", "w", "h", "object"])
110
+ st.dataframe(df)
111
+
112
+ else:
113
+ caption = parsed_answer.get("<CAPTION>", "No caption generated.")
114
+ st.subheader("Generated Caption:")
115
+ st.success(caption)