Update app.py
Browse files
app.py
CHANGED
@@ -5,12 +5,15 @@ import time
|
|
5 |
import streamlit as st
|
6 |
from PIL import Image
|
7 |
import torch
|
8 |
-
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration, AutoTokenizer, AutoModel
|
9 |
from diffusers import StableDiffusionPipeline
|
10 |
import cv2
|
11 |
import numpy as np
|
12 |
import logging
|
|
|
|
|
13 |
from io import BytesIO
|
|
|
14 |
|
15 |
# Logging setup
|
16 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
@@ -35,6 +38,8 @@ st.set_page_config(
|
|
35 |
# Initialize st.session_state
|
36 |
if 'captured_images' not in st.session_state:
|
37 |
st.session_state['captured_images'] = []
|
|
|
|
|
38 |
|
39 |
# Utility Functions
|
40 |
def generate_filename(sequence, ext="png"):
|
@@ -55,26 +60,26 @@ def update_gallery():
|
|
55 |
with cols[idx % 2]:
|
56 |
st.image(Image.open(file), caption=file, use_container_width=True)
|
57 |
|
58 |
-
# Model Loaders (
|
59 |
def load_ocr_qwen2vl():
|
60 |
model_id = "prithivMLmods/Qwen2-VL-OCR-2B-Instruct"
|
61 |
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
62 |
model = Qwen2VLForConditionalGeneration.from_pretrained(model_id, trust_remote_code=True, torch_dtype=torch.float32).to("cpu").eval()
|
63 |
return processor, model
|
64 |
|
65 |
-
def
|
66 |
-
model_id = "
|
67 |
-
|
68 |
-
model =
|
69 |
-
return
|
70 |
|
71 |
def load_image_gen():
|
72 |
-
model_id = "OFA-Sys/small-stable-diffusion-v0" #
|
73 |
pipeline = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float32).to("cpu")
|
74 |
return pipeline
|
75 |
|
76 |
def load_line_drawer():
|
77 |
-
# Simplified
|
78 |
def edge_detection(image):
|
79 |
img_np = np.array(image.convert("RGB"))
|
80 |
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
|
@@ -82,6 +87,52 @@ def load_line_drawer():
|
|
82 |
return Image.fromarray(edges)
|
83 |
return edge_detection
|
84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
# Main App
|
86 |
st.title("AI Vision Titans 🚀 (OCR, Gen, Drawings!)")
|
87 |
|
@@ -101,10 +152,9 @@ tab1, tab2, tab3, tab4 = st.tabs(["Camera Snap 📷", "Test OCR 🔍", "Test Ima
|
|
101 |
|
102 |
with tab1:
|
103 |
st.header("Camera Snap 📷")
|
104 |
-
|
105 |
cols = st.columns(2)
|
106 |
with cols[0]:
|
107 |
-
st.subheader("Camera 0")
|
108 |
cam0_img = st.camera_input("Take a picture - Cam 0", key="cam0")
|
109 |
if cam0_img:
|
110 |
filename = generate_filename(0)
|
@@ -115,24 +165,7 @@ with tab1:
|
|
115 |
logger.info(f"Saved snapshot from Camera 0: {filename}")
|
116 |
st.session_state['captured_images'].append(filename)
|
117 |
update_gallery()
|
118 |
-
if st.button(f"Capture {slice_count} Frames - Cam 0 📸"):
|
119 |
-
st.session_state['cam0_frames'] = []
|
120 |
-
for i in range(slice_count):
|
121 |
-
img = st.camera_input(f"Frame {i} - Cam 0", key=f"cam0_frame_{i}_{time.time()}")
|
122 |
-
if img:
|
123 |
-
filename = generate_filename(f"0_{i}")
|
124 |
-
if filename not in st.session_state['captured_images']:
|
125 |
-
with open(filename, "wb") as f:
|
126 |
-
f.write(img.getvalue())
|
127 |
-
st.session_state['cam0_frames'].append(filename)
|
128 |
-
logger.info(f"Saved frame {i} from Camera 0: {filename}")
|
129 |
-
time.sleep(1.0 / slice_count)
|
130 |
-
st.session_state['captured_images'].extend([f for f in st.session_state['cam0_frames'] if f not in st.session_state['captured_images']])
|
131 |
-
update_gallery()
|
132 |
-
for frame in st.session_state['cam0_frames']:
|
133 |
-
st.image(Image.open(frame), caption=frame, use_container_width=True)
|
134 |
with cols[1]:
|
135 |
-
st.subheader("Camera 1")
|
136 |
cam1_img = st.camera_input("Take a picture - Cam 1", key="cam1")
|
137 |
if cam1_img:
|
138 |
filename = generate_filename(1)
|
@@ -143,22 +176,28 @@ with tab1:
|
|
143 |
logger.info(f"Saved snapshot from Camera 1: {filename}")
|
144 |
st.session_state['captured_images'].append(filename)
|
145 |
update_gallery()
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
150 |
if img:
|
151 |
-
filename = generate_filename(f"
|
152 |
if filename not in st.session_state['captured_images']:
|
153 |
with open(filename, "wb") as f:
|
154 |
f.write(img.getvalue())
|
155 |
-
st.session_state['
|
156 |
-
logger.info(f"Saved frame {i}
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
|
163 |
with tab2:
|
164 |
st.header("Test OCR 🔍")
|
@@ -167,22 +206,15 @@ with tab2:
|
|
167 |
selected_image = st.selectbox("Select Image", captured_images, key="ocr_select")
|
168 |
image = Image.open(selected_image)
|
169 |
st.image(image, caption="Input Image", use_container_width=True)
|
170 |
-
ocr_model = st.selectbox("Select OCR Model", ["Qwen2-VL-OCR-2B", "
|
171 |
prompt = st.text_area("Prompt", "Extract text from the image", key="ocr_prompt")
|
172 |
if st.button("Run OCR 🚀", key="ocr_run"):
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
else: # GOT-OCR2_0
|
180 |
-
tokenizer, model = load_ocr_got()
|
181 |
-
with open(selected_image, "rb") as f:
|
182 |
-
img_bytes = f.read()
|
183 |
-
img = Image.open(BytesIO(img_bytes))
|
184 |
-
text = model.chat(tokenizer, img, ocr_type='ocr')
|
185 |
-
st.text_area("OCR Result", text, height=200, key="ocr_result")
|
186 |
else:
|
187 |
st.warning("No images captured yet. Use Camera Snap first!")
|
188 |
|
@@ -195,9 +227,12 @@ with tab3:
|
|
195 |
st.image(image, caption="Reference Image", use_container_width=True)
|
196 |
prompt = st.text_area("Prompt", "Generate a similar superhero image", key="gen_prompt")
|
197 |
if st.button("Run Image Gen 🚀", key="gen_run"):
|
198 |
-
|
199 |
-
|
200 |
-
|
|
|
|
|
|
|
201 |
else:
|
202 |
st.warning("No images captured yet. Use Camera Snap first!")
|
203 |
|
@@ -209,9 +244,12 @@ with tab4:
|
|
209 |
image = Image.open(selected_image)
|
210 |
st.image(image, caption="Input Image", use_container_width=True)
|
211 |
if st.button("Run Line Drawing 🚀", key="line_run"):
|
212 |
-
|
213 |
-
|
214 |
-
|
|
|
|
|
|
|
215 |
else:
|
216 |
st.warning("No images captured yet. Use Camera Snap first!")
|
217 |
|
|
|
5 |
import streamlit as st
|
6 |
from PIL import Image
|
7 |
import torch
|
8 |
+
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration, AutoTokenizer, AutoModel, TrOCRProcessor, VisionEncoderDecoderModel
|
9 |
from diffusers import StableDiffusionPipeline
|
10 |
import cv2
|
11 |
import numpy as np
|
12 |
import logging
|
13 |
+
import asyncio
|
14 |
+
import aiofiles
|
15 |
from io import BytesIO
|
16 |
+
import threading
|
17 |
|
18 |
# Logging setup
|
19 |
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
|
|
38 |
# Initialize st.session_state
|
39 |
if 'captured_images' not in st.session_state:
|
40 |
st.session_state['captured_images'] = []
|
41 |
+
if 'processing' not in st.session_state:
|
42 |
+
st.session_state['processing'] = {}
|
43 |
|
44 |
# Utility Functions
|
45 |
def generate_filename(sequence, ext="png"):
|
|
|
60 |
with cols[idx % 2]:
|
61 |
st.image(Image.open(file), caption=file, use_container_width=True)
|
62 |
|
63 |
+
# Model Loaders (Smaller, CPU-focused)
|
64 |
def load_ocr_qwen2vl():
|
65 |
model_id = "prithivMLmods/Qwen2-VL-OCR-2B-Instruct"
|
66 |
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
67 |
model = Qwen2VLForConditionalGeneration.from_pretrained(model_id, trust_remote_code=True, torch_dtype=torch.float32).to("cpu").eval()
|
68 |
return processor, model
|
69 |
|
70 |
+
def load_ocr_trocr():
|
71 |
+
model_id = "microsoft/trocr-small-handwritten" # Smaller, ~250 MB
|
72 |
+
processor = TrOCRProcessor.from_pretrained(model_id)
|
73 |
+
model = VisionEncoderDecoderModel.from_pretrained(model_id, torch_dtype=torch.float32).to("cpu").eval()
|
74 |
+
return processor, model
|
75 |
|
76 |
def load_image_gen():
|
77 |
+
model_id = "OFA-Sys/small-stable-diffusion-v0" # ~300 MB
|
78 |
pipeline = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float32).to("cpu")
|
79 |
return pipeline
|
80 |
|
81 |
def load_line_drawer():
|
82 |
+
# Simplified from your Torch Space (assuming edge detection)
|
83 |
def edge_detection(image):
|
84 |
img_np = np.array(image.convert("RGB"))
|
85 |
gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
|
|
|
87 |
return Image.fromarray(edges)
|
88 |
return edge_detection
|
89 |
|
90 |
+
# Async Processing Functions
|
91 |
+
async def process_ocr(image, prompt, model_name, output_file):
|
92 |
+
start_time = time.time()
|
93 |
+
status = st.empty()
|
94 |
+
status.text(f"Processing {model_name} OCR... (0s)")
|
95 |
+
if model_name == "Qwen2-VL-OCR-2B":
|
96 |
+
processor, model = load_ocr_qwen2vl()
|
97 |
+
inputs = processor(text=prompt, images=image, return_tensors="pt").to("cpu")
|
98 |
+
outputs = model.generate(**inputs, max_new_tokens=1024)
|
99 |
+
text = processor.batch_decode(outputs, skip_special_tokens=True)[0]
|
100 |
+
else: # TrOCR
|
101 |
+
processor, model = load_ocr_trocr()
|
102 |
+
pixel_values = processor(images=image, return_tensors="pt").pixel_values.to("cpu")
|
103 |
+
outputs = model.generate(pixel_values)
|
104 |
+
text = processor.batch_decode(outputs, skip_special_tokens=True)[0]
|
105 |
+
elapsed = int(time.time() - start_time)
|
106 |
+
status.text(f"{model_name} OCR completed in {elapsed}s!")
|
107 |
+
async with aiofiles.open(output_file, "w") as f:
|
108 |
+
await f.write(text)
|
109 |
+
st.session_state['captured_images'].append(output_file)
|
110 |
+
return text
|
111 |
+
|
112 |
+
async def process_image_gen(prompt, output_file):
|
113 |
+
start_time = time.time()
|
114 |
+
status = st.empty()
|
115 |
+
status.text("Processing Image Gen... (0s)")
|
116 |
+
pipeline = load_image_gen()
|
117 |
+
gen_image = pipeline(prompt, num_inference_steps=20).images[0] # Reduced steps for speed
|
118 |
+
elapsed = int(time.time() - start_time)
|
119 |
+
status.text(f"Image Gen completed in {elapsed}s!")
|
120 |
+
gen_image.save(output_file)
|
121 |
+
st.session_state['captured_images'].append(output_file)
|
122 |
+
return gen_image
|
123 |
+
|
124 |
+
async def process_line_drawing(image, output_file):
|
125 |
+
start_time = time.time()
|
126 |
+
status = st.empty()
|
127 |
+
status.text("Processing Line Drawing... (0s)")
|
128 |
+
edge_fn = load_line_drawer()
|
129 |
+
line_drawing = edge_fn(image)
|
130 |
+
elapsed = int(time.time() - start_time)
|
131 |
+
status.text(f"Line Drawing completed in {elapsed}s!")
|
132 |
+
line_drawing.save(output_file)
|
133 |
+
st.session_state['captured_images'].append(output_file)
|
134 |
+
return line_drawing
|
135 |
+
|
136 |
# Main App
|
137 |
st.title("AI Vision Titans 🚀 (OCR, Gen, Drawings!)")
|
138 |
|
|
|
152 |
|
153 |
with tab1:
|
154 |
st.header("Camera Snap 📷")
|
155 |
+
st.subheader("Single Capture")
|
156 |
cols = st.columns(2)
|
157 |
with cols[0]:
|
|
|
158 |
cam0_img = st.camera_input("Take a picture - Cam 0", key="cam0")
|
159 |
if cam0_img:
|
160 |
filename = generate_filename(0)
|
|
|
165 |
logger.info(f"Saved snapshot from Camera 0: {filename}")
|
166 |
st.session_state['captured_images'].append(filename)
|
167 |
update_gallery()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
168 |
with cols[1]:
|
|
|
169 |
cam1_img = st.camera_input("Take a picture - Cam 1", key="cam1")
|
170 |
if cam1_img:
|
171 |
filename = generate_filename(1)
|
|
|
176 |
logger.info(f"Saved snapshot from Camera 1: {filename}")
|
177 |
st.session_state['captured_images'].append(filename)
|
178 |
update_gallery()
|
179 |
+
|
180 |
+
st.subheader("Burst Capture")
|
181 |
+
slice_count = st.number_input("Number of Frames", min_value=1, max_value=20, value=10, key="burst_count")
|
182 |
+
if st.button("Start Burst Capture 📸"):
|
183 |
+
st.session_state['burst_frames'] = []
|
184 |
+
placeholder = st.empty()
|
185 |
+
for i in range(slice_count):
|
186 |
+
with placeholder.container():
|
187 |
+
st.write(f"Capturing frame {i+1}/{slice_count}...")
|
188 |
+
img = st.camera_input(f"Frame {i}", key=f"burst_{i}_{time.time()}")
|
189 |
if img:
|
190 |
+
filename = generate_filename(f"burst_{i}")
|
191 |
if filename not in st.session_state['captured_images']:
|
192 |
with open(filename, "wb") as f:
|
193 |
f.write(img.getvalue())
|
194 |
+
st.session_state['burst_frames'].append(filename)
|
195 |
+
logger.info(f"Saved burst frame {i}: {filename}")
|
196 |
+
st.image(Image.open(filename), caption=filename, use_container_width=True)
|
197 |
+
time.sleep(0.5) # Small delay for visibility
|
198 |
+
st.session_state['captured_images'].extend([f for f in st.session_state['burst_frames'] if f not in st.session_state['captured_images']])
|
199 |
+
update_gallery()
|
200 |
+
placeholder.success(f"Captured {len(st.session_state['burst_frames'])} frames!")
|
201 |
|
202 |
with tab2:
|
203 |
st.header("Test OCR 🔍")
|
|
|
206 |
selected_image = st.selectbox("Select Image", captured_images, key="ocr_select")
|
207 |
image = Image.open(selected_image)
|
208 |
st.image(image, caption="Input Image", use_container_width=True)
|
209 |
+
ocr_model = st.selectbox("Select OCR Model", ["Qwen2-VL-OCR-2B", "TrOCR-Small"], key="ocr_model_select")
|
210 |
prompt = st.text_area("Prompt", "Extract text from the image", key="ocr_prompt")
|
211 |
if st.button("Run OCR 🚀", key="ocr_run"):
|
212 |
+
output_file = generate_filename("ocr_output", "txt")
|
213 |
+
st.session_state['processing']['ocr'] = True
|
214 |
+
result = asyncio.run(process_ocr(image, prompt, ocr_model, output_file))
|
215 |
+
st.text_area("OCR Result", result, height=200, key="ocr_result")
|
216 |
+
st.success(f"OCR output saved to {output_file}")
|
217 |
+
st.session_state['processing']['ocr'] = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
218 |
else:
|
219 |
st.warning("No images captured yet. Use Camera Snap first!")
|
220 |
|
|
|
227 |
st.image(image, caption="Reference Image", use_container_width=True)
|
228 |
prompt = st.text_area("Prompt", "Generate a similar superhero image", key="gen_prompt")
|
229 |
if st.button("Run Image Gen 🚀", key="gen_run"):
|
230 |
+
output_file = generate_filename("gen_output", "png")
|
231 |
+
st.session_state['processing']['gen'] = True
|
232 |
+
result = asyncio.run(process_image_gen(prompt, output_file))
|
233 |
+
st.image(result, caption="Generated Image", use_container_width=True)
|
234 |
+
st.success(f"Image saved to {output_file}")
|
235 |
+
st.session_state['processing']['gen'] = False
|
236 |
else:
|
237 |
st.warning("No images captured yet. Use Camera Snap first!")
|
238 |
|
|
|
244 |
image = Image.open(selected_image)
|
245 |
st.image(image, caption="Input Image", use_container_width=True)
|
246 |
if st.button("Run Line Drawing 🚀", key="line_run"):
|
247 |
+
output_file = generate_filename("line_output", "png")
|
248 |
+
st.session_state['processing']['line'] = True
|
249 |
+
result = asyncio.run(process_line_drawing(image, output_file))
|
250 |
+
st.image(result, caption="Line Drawing", use_container_width=True)
|
251 |
+
st.success(f"Line drawing saved to {output_file}")
|
252 |
+
st.session_state['processing']['line'] = False
|
253 |
else:
|
254 |
st.warning("No images captured yet. Use Camera Snap first!")
|
255 |
|