Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
from PIL import Image
|
4 |
+
import random
|
5 |
+
from io import BytesIO
|
6 |
+
import datetime
|
7 |
+
import base64
|
8 |
+
|
9 |
+
# Adjust Streamlit layout to wide mode
|
10 |
+
st.set_page_config(layout="wide")
|
11 |
+
|
12 |
+
# Function to arrange images dynamically
|
13 |
+
def arrange_images(image_files, canvas_size=(3000, 3000)):
|
14 |
+
if not image_files:
|
15 |
+
return None, []
|
16 |
+
|
17 |
+
positions = [] # Keeps track of image positions (x1, y1, x2, y2)
|
18 |
+
canvas = Image.new("RGBA", canvas_size, "white")
|
19 |
+
room_details = [] # To store room layout details
|
20 |
+
|
21 |
+
def get_center(pos):
|
22 |
+
"""Calculate center of a bounding box (x1, y1, x2, y2)."""
|
23 |
+
return ((pos[0] + pos[2]) // 2, (pos[1] + pos[3]) // 2)
|
24 |
+
|
25 |
+
def does_overlap(new_box, existing_boxes):
|
26 |
+
"""Check if a new bounding box overlaps any existing boxes."""
|
27 |
+
for box in existing_boxes:
|
28 |
+
if (
|
29 |
+
new_box[0] < box[2]
|
30 |
+
and new_box[2] > box[0]
|
31 |
+
and new_box[1] < box[3]
|
32 |
+
and new_box[3] > box[1]
|
33 |
+
):
|
34 |
+
return True
|
35 |
+
return False
|
36 |
+
|
37 |
+
# Place the first image at the center of the canvas
|
38 |
+
first_img_path = os.path.join(map_dir, image_files[0])
|
39 |
+
with Image.open(first_img_path) as img:
|
40 |
+
width, height = img.size
|
41 |
+
x1 = (canvas_size[0] - width) // 2
|
42 |
+
y1 = (canvas_size[1] - height) // 2
|
43 |
+
x2, y2 = x1 + width, y1 + height
|
44 |
+
positions.append((x1, y1, x2, y2))
|
45 |
+
canvas.paste(img, (x1, y1))
|
46 |
+
room_details.append(f"Room 1: {image_files[0]} at center")
|
47 |
+
|
48 |
+
# Place remaining images
|
49 |
+
for idx, img_file in enumerate(image_files[1:], start=2):
|
50 |
+
placed = False
|
51 |
+
img_path = os.path.join(map_dir, img_file)
|
52 |
+
|
53 |
+
with Image.open(img_path) as img:
|
54 |
+
width, height = img.size
|
55 |
+
|
56 |
+
while not placed:
|
57 |
+
target_box = random.choice(positions)
|
58 |
+
target_center = get_center(target_box)
|
59 |
+
side = random.choice(["top", "bottom", "left", "right"])
|
60 |
+
|
61 |
+
if side == "top":
|
62 |
+
x1 = target_center[0] - width // 2
|
63 |
+
y1 = target_box[1] - height
|
64 |
+
elif side == "bottom":
|
65 |
+
x1 = target_center[0] - width // 2
|
66 |
+
y1 = target_box[3]
|
67 |
+
elif side == "left":
|
68 |
+
x1 = target_box[0] - width
|
69 |
+
y1 = target_center[1] - height // 2
|
70 |
+
elif side == "right":
|
71 |
+
x1 = target_box[2]
|
72 |
+
y1 = target_center[1] - height // 2
|
73 |
+
|
74 |
+
x2, y2 = x1 + width, y1 + height
|
75 |
+
|
76 |
+
if not does_overlap((x1, y1, x2, y2), positions):
|
77 |
+
positions.append((x1, y1, x2, y2))
|
78 |
+
canvas.paste(img, (x1, y1))
|
79 |
+
room_details.append(f"Room {idx}: {img_file} at ({x1}, {y1})")
|
80 |
+
placed = True
|
81 |
+
|
82 |
+
buffer = BytesIO()
|
83 |
+
canvas.save(buffer, format="PNG")
|
84 |
+
buffer.seek(0)
|
85 |
+
return buffer, canvas, room_details
|
86 |
+
|
87 |
+
# Function to create a base64 link
|
88 |
+
def create_base64_download_link(file_content, filename, file_type):
|
89 |
+
b64 = base64.b64encode(file_content.encode() if file_type == "txt" else file_content).decode()
|
90 |
+
return f"[π₯ Download {filename}](data:application/{file_type};base64,{b64})"
|
91 |
+
|
92 |
+
# Sidebar Title
|
93 |
+
st.sidebar.markdown("#### π° Dynamic Dungeon Map Generator")
|
94 |
+
|
95 |
+
# Directory for images
|
96 |
+
map_dir = "."
|
97 |
+
canvas_size = 3000
|
98 |
+
|
99 |
+
# Initialize session state
|
100 |
+
if "layout_image" not in st.session_state:
|
101 |
+
st.session_state["layout_image"] = None
|
102 |
+
if "canvas" not in st.session_state:
|
103 |
+
st.session_state["canvas"] = None
|
104 |
+
if "room_details" not in st.session_state:
|
105 |
+
st.session_state["room_details"] = []
|
106 |
+
if "saved_files" not in st.session_state:
|
107 |
+
st.session_state["saved_files"] = []
|
108 |
+
|
109 |
+
# Generate map if layout_image is empty
|
110 |
+
if st.session_state["layout_image"] is None:
|
111 |
+
image_files = [f for f in os.listdir(map_dir) if f.endswith(".png")]
|
112 |
+
if image_files:
|
113 |
+
layout_image, canvas, room_details = arrange_images(image_files, canvas_size=(canvas_size, canvas_size))
|
114 |
+
st.session_state["layout_image"] = layout_image
|
115 |
+
st.session_state["canvas"] = canvas
|
116 |
+
st.session_state["room_details"] = room_details
|
117 |
+
|
118 |
+
# Sidebar Controls
|
119 |
+
if st.sidebar.button("πΎ Save Map"):
|
120 |
+
now = datetime.datetime.now()
|
121 |
+
filename_png = f"dungeon_map_{now.strftime('%Y%m%d_%H%M%S')}.png"
|
122 |
+
filename_txt = f"room_layout_{now.strftime('%Y%m%d_%H%M%S')}.txt"
|
123 |
+
|
124 |
+
# Save the PNG map
|
125 |
+
st.session_state["canvas"].save(filename_png)
|
126 |
+
st.sidebar.success(f"Map saved as {filename_png}")
|
127 |
+
|
128 |
+
# Save room details as a text file
|
129 |
+
room_details_content = "\n".join(st.session_state["room_details"])
|
130 |
+
with open(filename_txt, "w") as f:
|
131 |
+
f.write(room_details_content)
|
132 |
+
st.sidebar.success(f"Room layout saved as {filename_txt}")
|
133 |
+
|
134 |
+
# Generate base64 download links
|
135 |
+
with open(filename_png, "rb") as f:
|
136 |
+
png_base64 = create_base64_download_link(f.read(), filename_png, "octet-stream")
|
137 |
+
txt_base64 = create_base64_download_link(room_details_content, filename_txt, "txt")
|
138 |
+
|
139 |
+
# Add files to save history
|
140 |
+
st.session_state["saved_files"].append((png_base64, txt_base64))
|
141 |
+
|
142 |
+
if st.sidebar.button("πΊοΈ Regenerate Map"):
|
143 |
+
image_files = [f for f in os.listdir(map_dir) if f.endswith(".png")]
|
144 |
+
if image_files:
|
145 |
+
layout_image, canvas, room_details = arrange_images(image_files, canvas_size=(canvas_size, canvas_size))
|
146 |
+
st.session_state["layout_image"] = layout_image
|
147 |
+
st.session_state["canvas"] = canvas
|
148 |
+
st.session_state["room_details"] = room_details
|
149 |
+
st.rerun()
|
150 |
+
|
151 |
+
# Display save history in the sidebar
|
152 |
+
st.sidebar.markdown("### π Save History")
|
153 |
+
for idx, (png_link, txt_link) in enumerate(st.session_state["saved_files"], start=1):
|
154 |
+
st.sidebar.markdown(f"{idx}. {png_link} | {txt_link}")
|
155 |
+
|
156 |
+
# Zoom Controls
|
157 |
+
st.sidebar.title("Zoom")
|
158 |
+
show_zoomed = st.sidebar.checkbox("Show Zoomed Version")
|
159 |
+
zoom_level = st.sidebar.slider("Zoom Level", min_value=0.1, max_value=2.0, value=1.0, step=0.1)
|
160 |
+
|
161 |
+
if show_zoomed and st.session_state["canvas"] is not None:
|
162 |
+
zoomed_canvas = st.session_state["canvas"].resize(
|
163 |
+
(int(canvas_size * zoom_level), int(canvas_size * zoom_level)),
|
164 |
+
resample=Image.Resampling.LANCZOS,
|
165 |
+
)
|
166 |
+
buffer = BytesIO()
|
167 |
+
zoomed_canvas.save(buffer, format="PNG")
|
168 |
+
buffer.seek(0)
|
169 |
+
st.image(
|
170 |
+
buffer,
|
171 |
+
caption=f"Zoomed Dungeon Map Layout (Zoom Level: {zoom_level}x)",
|
172 |
+
use_container_width=False,
|
173 |
+
output_format="PNG",
|
174 |
+
)
|
175 |
+
else:
|
176 |
+
st.image(
|
177 |
+
st.session_state["layout_image"],
|
178 |
+
caption="Generated Dungeon Map Layout",
|
179 |
+
use_container_width=True,
|
180 |
+
output_format="PNG",
|
181 |
+
)
|