Dharini Baskaran commited on
Commit Β·
873ac58
1
Parent(s): 30bfac2
trying gradio
Browse filesFiles changed (4)
- README.md+4-4
- app.py+61-151
- app_streamlit.pyAdded+200
- requirements.txt+2-1
1234567891011121314---title: 2D Floorplan Vectorizeremoji: πcolorFrom: bluecolorTo: greensdk: dockerapp_file: app.pypinned: false---# 2D Floorplan VectorizerA Streamlit web app that allows you to upload 2D floorplan images and automatically vectorize them into COCO-style annotations using a trained Mask R-CNN model.1234567891011121314---title: 2D Floorplan Vectorizeremoji: πcolorFrom: greencolorTo: bluesdk: gradiosdk_version: "4.15.0"app_file: app.pypinned: false---# 2D Floorplan VectorizerA Streamlit web app that allows you to upload 2D floorplan images and automatically vectorize them into COCO-style annotations using a trained Mask R-CNN model.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200import streamlit as stimport jsonimport timefrom PIL import Imageimport osimport sysimport shutilimport gdownfrom io import BytesIO# ==================================# SETUP# ==================================print("π Streamlit App Starting...")BASE_DIR = os.path.dirname(os.path.abspath(__file__))# Setup PathsUPLOAD_DIR = "/tmp/uploads/"MODEL_DIR = os.path.join(BASE_DIR, "rcnn_model", "scripts")JSON_DIR = "/tmp/results/"OUTPUT_DIR = "/tmp/output/"SAMPLE_DIR = os.path.join(BASE_DIR, "rcnn_model", "sample")logo_path = os.path.join(BASE_DIR, "public", "logo.png")model_path = os.path.join(OUTPUT_DIR, "model_final.pth")# Google Drive file download linkGOOGLE_DRIVE_FILE_ID = "1yr64AOgaYZPTcQzG6cxG6lWBENHR9qjW"GDRIVE_URL = f"https://drive.google.com/uc?id={GOOGLE_DRIVE_FILE_ID}"# Create necessary foldersos.makedirs(UPLOAD_DIR, exist_ok=True)os.makedirs(JSON_DIR, exist_ok=True)os.makedirs(OUTPUT_DIR, exist_ok=True)# ==================================# DOWNLOAD MODEL IF MISSING# ==================================if not os.path.exists(model_path):print("π Model file not found! Downloading from Google Drive...")try:gdown.download(GDRIVE_URL, model_path, quiet=False)print("β Model downloaded successfully.")except Exception as e:print(f"β Failed to download model: {e}")# ==================================# IMPORT MODEL RUNNER# ==================================sys.path.append(MODEL_DIR)from rcnn_model.scripts.rcnn_run import main, write_config# ==================================# PAGE CONFIG# ==================================st.set_page_config(page_title="2D Floorplan Vectorizer",layout="wide",initial_sidebar_state="collapsed")# ==================================# HEADER# ==================================st.image(logo_path, width=250)st.markdown("<div class='header-title'>2D Floorplan Vectorizer</div>", unsafe_allow_html=True)# ==================================# FILE UPLOAD SECTION# ==================================st.subheader("Upload your Floorplan Image")uploaded_file = st.file_uploader("Choose an image", type=["png", "jpg", "jpeg"])# Initialize session stateif "processing_complete" not in st.session_state:st.session_state.processing_complete = Falseif "json_output" not in st.session_state:st.session_state.json_output = None# ==================================# IMAGE + JSON Layout# ==================================col1, col2 = st.columns([1, 2])# ==================================# MAIN LOGIC# ==================================if uploaded_file is not None:print("π€ File Uploaded:", uploaded_file.name)image_bytes = uploaded_file.read()img = Image.open(BytesIO(image_bytes)).convert("RGB")uploaded_path = os.path.join(UPLOAD_DIR, uploaded_file.name)with open(uploaded_path, "wb") as f:f.write(uploaded_file.getbuffer())print("β Uploaded file saved at:", uploaded_path)with col1:st.markdown("<div class='upload-container'>", unsafe_allow_html=True)st.image(Image.open(uploaded_path), caption="Uploaded Image", use_container_width=True)st.markdown("</div>", unsafe_allow_html=True)with col2:if not st.session_state.processing_complete:status_placeholder = st.empty()status_placeholder.info("β³ Model is processing the uploaded image...")progress_bar = st.progress(0)status_text = st.empty()# === π₯ Model Run Here ===input_image = uploaded_pathoutput_json_name = uploaded_file.name.replace(".png", "_result.json").replace(".jpg", "_result.json").replace(".jpeg", "_result.json")output_image_name = uploaded_file.name.replace(".png", "_result.png").replace(".jpg", "_result.png").replace(".jpeg", "_result.png")output_json_path = os.path.join(JSON_DIR, output_json_name)output_image_path = os.path.join(JSON_DIR, output_image_name)cfg = write_config()print("βοΈ Model config created. Running model...")# Simulate progressfor i in range(1, 30):time.sleep(0.01)progress_bar.progress(i)status_text.text(f"Preprocessing: {i}%")# Run modelmain(cfg, input_image, output_json_path, output_image_path)print("β Model run complete.")while not os.path.exists(output_json_path):print("Waiting for JSON output...")time.sleep(0.5)for i in range(30, 100):time.sleep(0.01)progress_bar.progress(i)status_text.text(f"Postprocessing: {i}%")progress_bar.empty()status_text.text("β Processing Complete!")status_placeholder.success("β Model finished and JSON is ready!")# Read generated JSONif os.path.exists(output_json_path):with open(output_json_path, "r") as jf:st.session_state.json_output = json.load(jf)print("π JSON Output Loaded Successfully.")else:st.session_state.json_output = {"error": "JSON output not generated."}print("β JSON output missing.")st.session_state.processing_complete = True# ==================================# DISPLAY OUTPUTS# ==================================out_col1, out_col2 = st.columns(2)with out_col1:if os.path.exists(output_image_path):with open(output_image_path, "rb") as img_file:image = Image.open(img_file)st.image(image, caption="πΌ Output Vectorized Image", use_container_width=True)img_file.seek(0)st.download_button(label="Download Output Image",data=img_file,file_name="floorplan_output.png",mime="image/png")if os.path.exists(output_json_path):json_str = json.dumps(st.session_state.json_output, indent=4)st.download_button(label="Download JSON",data=json_str,file_name="floorplan_output.json",mime="application/json")with out_col2:st.markdown("<div class='json-container'>", unsafe_allow_html=True)st.json(st.session_state.json_output)st.markdown("</div>", unsafe_allow_html=True)else:st.warning("β οΈ No image uploaded yet.")st.session_state.processing_complete = False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110import gradio as grimport osimport sysimport jsonimport shutilimport gdownimport timefrom PIL import Imagefrom io import BytesIO# ==================================# SETUP# ==================================print("π Gradio App Starting...")BASE_DIR = os.path.dirname(os.path.abspath(__file__))# PathsUPLOAD_DIR = "/tmp/uploads/"JSON_DIR = "/tmp/results/"OUTPUT_DIR = "/tmp/output/"MODEL_DIR = os.path.join(BASE_DIR, "rcnn_model", "scripts")logo_path = os.path.join(BASE_DIR, "public", "logo.png")model_path = os.path.join(OUTPUT_DIR, "model_final.pth")# Google Drive modelGOOGLE_DRIVE_FILE_ID = "1yr64AOgaYZPTcQzG6cxG6lWBENHR9qjW"GDRIVE_URL = f"https://drive.google.com/uc?id={GOOGLE_DRIVE_FILE_ID}"# Create foldersos.makedirs(UPLOAD_DIR, exist_ok=True)os.makedirs(JSON_DIR, exist_ok=True)os.makedirs(OUTPUT_DIR, exist_ok=True)# Download model if missingif not os.path.exists(model_path):print("π Model file not found! Downloading...")try:gdown.download(GDRIVE_URL, model_path, quiet=False)print("β Model downloaded successfully.")except Exception as e:print(f"β Failed to download model: {e}")# Import modelsys.path.append(MODEL_DIR)from rcnn_run import main, write_configcfg = write_config()# ==================================# MAIN PREDICTION FUNCTION# ==================================def predict(uploaded_file):if uploaded_file is None:return None, None, "No file uploaded."# Save uploaded imageinput_bytes = uploaded_file.read()img = Image.open(BytesIO(input_bytes)).convert("RGB")input_filename = uploaded_file.nameuploaded_path = os.path.join(UPLOAD_DIR, input_filename)img.save(uploaded_path)print(f"β Image saved to {uploaded_path}")# Prepare output pathsoutput_json_name = input_filename.replace(".png", "_result.json").replace(".jpg", "_result.json").replace(".jpeg", "_result.json")output_image_name = input_filename.replace(".png", "_result.png").replace(".jpg", "_result.png").replace(".jpeg", "_result.png")output_json_path = os.path.join(JSON_DIR, output_json_name)output_image_path = os.path.join(JSON_DIR, output_image_name)# Run modelmain(cfg, uploaded_path, output_json_path, output_image_path)# Read outputsresult_img = Image.open(output_image_path) if os.path.exists(output_image_path) else Noneresult_json = {}if os.path.exists(output_json_path):with open(output_json_path, "r") as jf:result_json = json.load(jf)return result_img, json.dumps(result_json, indent=2), None# ==================================# GRADIO UI# ==================================with gr.Blocks() as demo:gr.Markdown("<h1 style='text-align: center;'>π Inovonics 2D Floorplan Vectorizer</h1>")with gr.Row():with gr.Column():uploaded_file = gr.File(label="Upload your Floorplan Image", type="file")run_button = gr.Button("Run Vectorizer π₯")with gr.Column():output_image = gr.Image(label="πΌ Output Vectorized Image")output_json = gr.JSON(label="π§Ύ Output JSON")error_output = gr.Textbox(label="Error Message", visible=False)run_button.click(predict,inputs=[uploaded_file],outputs=[output_image, output_json, error_output])demo.launch()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200import streamlit as stimport jsonimport timefrom PIL import Imageimport osimport sysimport shutilimport gdownfrom io import BytesIO
# ==================================# SETUP# ==================================
print("π Streamlit App Starting...")
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Setup PathsUPLOAD_DIR = "/tmp/uploads/"MODEL_DIR = os.path.join(BASE_DIR, "rcnn_model", "scripts")JSON_DIR = "/tmp/results/"OUTPUT_DIR = "/tmp/output/"SAMPLE_DIR = os.path.join(BASE_DIR, "rcnn_model", "sample")logo_path = os.path.join(BASE_DIR, "public", "logo.png")model_path = os.path.join(OUTPUT_DIR, "model_final.pth")
# Google Drive file download linkGOOGLE_DRIVE_FILE_ID = "1yr64AOgaYZPTcQzG6cxG6lWBENHR9qjW"GDRIVE_URL = f"https://drive.google.com/uc?id={GOOGLE_DRIVE_FILE_ID}"
# Create necessary foldersos.makedirs(UPLOAD_DIR, exist_ok=True)os.makedirs(JSON_DIR, exist_ok=True)os.makedirs(OUTPUT_DIR, exist_ok=True)
# ==================================# DOWNLOAD MODEL IF MISSING# ==================================
if not os.path.exists(model_path): print("π Model file not found! Downloading from Google Drive...") try: gdown.download(GDRIVE_URL, model_path, quiet=False) print("β
Model downloaded successfully.") except Exception as e: print(f"β Failed to download model: {e}")
# ==================================# IMPORT MODEL RUNNER# ==================================
sys.path.append(MODEL_DIR)from rcnn_model.scripts.rcnn_run import main, write_config
# ==================================# PAGE CONFIG# ==================================
st.set_page_config( page_title="2D Floorplan Vectorizer", layout="wide", initial_sidebar_state="collapsed")
# ==================================# HEADER# ==================================
st.image(logo_path, width=250)st.markdown("<div class='header-title'>2D Floorplan Vectorizer</div>", unsafe_allow_html=True)
# ==================================# FILE UPLOAD SECTION# ==================================
st.subheader("Upload your Floorplan Image")uploaded_file = st.file_uploader("Choose an image", type=["png", "jpg", "jpeg"])
# Initialize session stateif "processing_complete" not in st.session_state: st.session_state.processing_complete = Falseif "json_output" not in st.session_state: st.session_state.json_output = None
# ==================================# IMAGE + JSON Layout# ==================================
col1, col2 = st.columns([1, 2])
# ==================================# MAIN LOGIC# ==================================
if uploaded_file is not None: print("π€ File Uploaded:", uploaded_file.name)
image_bytes = uploaded_file.read() img = Image.open(BytesIO(image_bytes)).convert("RGB")
uploaded_path = os.path.join(UPLOAD_DIR, uploaded_file.name) with open(uploaded_path, "wb") as f: f.write(uploaded_file.getbuffer()) print("β
Uploaded file saved at:", uploaded_path)
with col1: st.markdown("<div class='upload-container'>", unsafe_allow_html=True) st.image(Image.open(uploaded_path), caption="Uploaded Image", use_container_width=True) st.markdown("</div>", unsafe_allow_html=True)
with col2: if not st.session_state.processing_complete: status_placeholder = st.empty() status_placeholder.info("β³ Model is processing the uploaded image...") progress_bar = st.progress(0) status_text = st.empty()
# === π₯ Model Run Here === input_image = uploaded_path output_json_name = uploaded_file.name.replace(".png", "_result.json").replace(".jpg", "_result.json").replace(".jpeg", "_result.json") output_image_name = uploaded_file.name.replace(".png", "_result.png").replace(".jpg", "_result.png").replace(".jpeg", "_result.png")
output_json_path = os.path.join(JSON_DIR, output_json_name) output_image_path = os.path.join(JSON_DIR, output_image_name)
cfg = write_config() print("βοΈ Model config created. Running model...")
# Simulate progress for i in range(1, 30): time.sleep(0.01) progress_bar.progress(i) status_text.text(f"Preprocessing: {i}%")
# Run model main(cfg, input_image, output_json_path, output_image_path) print("β
Model run complete.")
while not os.path.exists(output_json_path): print("Waiting for JSON output...") time.sleep(0.5)
for i in range(30, 100): time.sleep(0.01) progress_bar.progress(i) status_text.text(f"Postprocessing: {i}%")
progress_bar.empty() status_text.text("β
Processing Complete!") status_placeholder.success("β
Model finished and JSON is ready!")
# Read generated JSON if os.path.exists(output_json_path): with open(output_json_path, "r") as jf: st.session_state.json_output = json.load(jf) print("π JSON Output Loaded Successfully.") else: st.session_state.json_output = {"error": "JSON output not generated."} print("β JSON output missing.")
st.session_state.processing_complete = True
# ================================== # DISPLAY OUTPUTS # ==================================
out_col1, out_col2 = st.columns(2)
with out_col1: if os.path.exists(output_image_path): with open(output_image_path, "rb") as img_file: image = Image.open(img_file) st.image(image, caption="πΌ Output Vectorized Image", use_container_width=True)
img_file.seek(0) st.download_button( label="Download Output Image", data=img_file, file_name="floorplan_output.png", mime="image/png" )
if os.path.exists(output_json_path): json_str = json.dumps(st.session_state.json_output, indent=4) st.download_button( label="Download JSON", data=json_str, file_name="floorplan_output.json", mime="application/json" )
with out_col2: st.markdown("<div class='json-container'>", unsafe_allow_html=True) st.json(st.session_state.json_output) st.markdown("</div>", unsafe_allow_html=True)
else: st.warning("β οΈ No image uploaded yet.") st.session_state.processing_complete = False7 unmodified lines8910117 unmodified linesmatplotliblabelme2coconumpyfrom_root7 unmodified lines891011127 unmodified linesmatplotliblabelme2coconumpyfrom_rootgradio
README.md+4-4
app.py+61-151
app_streamlit.pyAdded+200
requirements.txt+2-1