Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,8 @@
|
|
1 |
import io
|
2 |
import os
|
3 |
-
import math
|
4 |
import re
|
5 |
-
from collections import Counter
|
6 |
from datetime import datetime
|
|
|
7 |
|
8 |
import pandas as pd
|
9 |
import streamlit as st
|
@@ -20,7 +19,7 @@ st.set_page_config(
|
|
20 |
|
21 |
st.title("🖼️ Image → PDF • Full-Page & Custom Layout Generator")
|
22 |
st.markdown(
|
23 |
-
"Upload images, filter by orientation, reorder visually, and generate
|
24 |
)
|
25 |
|
26 |
# --- Sidebar: Page Settings -----------------------------
|
@@ -45,7 +44,7 @@ BASE_WIDTH_PT = st.sidebar.slider(
|
|
45 |
)
|
46 |
page_width = BASE_WIDTH_PT
|
47 |
page_height = int(BASE_WIDTH_PT * (rh / rw))
|
48 |
-
st.sidebar.markdown(f"**
|
49 |
|
50 |
# --- Main: Upload, Filter & Reorder -------------------
|
51 |
st.header("2️⃣ Upload, Filter & Reorder Images")
|
@@ -66,7 +65,7 @@ if uploaded:
|
|
66 |
"height": h,
|
67 |
"aspect_ratio": ar,
|
68 |
"orientation": orient,
|
69 |
-
"order": idx
|
70 |
})
|
71 |
df = pd.DataFrame(records)
|
72 |
dims = st.sidebar.multiselect(
|
@@ -74,9 +73,10 @@ if uploaded:
|
|
74 |
default=["Landscape","Portrait","Square"]
|
75 |
)
|
76 |
df = df[df["orientation"].isin(dims)].reset_index(drop=True)
|
77 |
-
|
|
|
78 |
st.dataframe(df.style.format({"aspect_ratio": "{:.2f}"}), use_container_width=True)
|
79 |
-
st.markdown("
|
80 |
try:
|
81 |
edited = st.experimental_data_editor(df, num_rows="fixed", use_container_width=True)
|
82 |
ordered_df = edited
|
@@ -92,116 +92,67 @@ if uploaded:
|
|
92 |
use_container_width=True,
|
93 |
)
|
94 |
ordered_df = edited.sort_values("order").reset_index(drop=True)
|
|
|
95 |
name2file = {f.name: f for f in uploaded}
|
96 |
ordered_files = [name2file[n] for n in ordered_df["filename"] if n in name2file]
|
97 |
|
98 |
-
# --- Utility:
|
99 |
-
def
|
100 |
-
|
101 |
-
|
102 |
-
stem = os.path.splitext(fn)[0]
|
103 |
-
words += re.findall(r"\w+", stem.lower())
|
104 |
-
return [w for w,_ in Counter(words).most_common(n)]
|
105 |
-
|
106 |
-
def first_n_words_ordered(names, n=5):
|
107 |
-
words = []
|
108 |
-
for fn in names:
|
109 |
-
stem = os.path.splitext(fn)[0]
|
110 |
-
tokens = re.findall(r"\w+", stem)
|
111 |
-
for t in tokens:
|
112 |
-
if len(words) < n:
|
113 |
-
words.append(t)
|
114 |
-
else:
|
115 |
-
break
|
116 |
-
if len(words) >= n:
|
117 |
-
break
|
118 |
-
return words
|
119 |
-
|
120 |
-
# --- PDF Creation: Full Page ----------------------------
|
121 |
-
def make_fullpage_pdf(images, w_pt, h_pt):
|
122 |
-
buf = io.BytesIO()
|
123 |
-
c = canvas.Canvas(buf, pagesize=(w_pt, h_pt))
|
124 |
-
for f in images:
|
125 |
-
im = Image.open(f)
|
126 |
-
iw, ih = im.size
|
127 |
-
scale = min(w_pt/iw, h_pt/ih)
|
128 |
-
new_w, new_h = iw*scale, ih*scale
|
129 |
-
x = (w_pt - new_w)/2
|
130 |
-
y = (h_pt - new_h)/2
|
131 |
-
im = im.resize((int(new_w), int(new_h)), Image.LANCZOS)
|
132 |
-
c.drawImage(ImageReader(im), x, y, new_w, new_h, preserveAspectRatio=False, mask='auto')
|
133 |
-
c.showPage()
|
134 |
-
c.save(); buf.seek(0)
|
135 |
-
return buf.getvalue()
|
136 |
|
137 |
# --- PDF Creation: Image-sized + Captions --------------
|
138 |
def make_image_sized_pdf(images):
|
139 |
-
|
140 |
-
c = canvas.Canvas(
|
141 |
-
for f in images:
|
142 |
im = Image.open(f)
|
143 |
iw, ih = im.size
|
144 |
-
#
|
145 |
cap_h = 20
|
146 |
page_w, page_h = iw, ih + cap_h
|
147 |
c.setPageSize((page_w, page_h))
|
148 |
-
#
|
149 |
c.drawImage(ImageReader(im), 0, cap_h, iw, ih, preserveAspectRatio=True, mask='auto')
|
150 |
-
# caption
|
151 |
-
caption =
|
152 |
c.setFont("Helvetica", 12)
|
153 |
c.drawCentredString(page_w/2, cap_h/2, caption)
|
|
|
|
|
|
|
154 |
c.showPage()
|
155 |
-
c.save()
|
156 |
-
|
|
|
157 |
|
158 |
# --- Generate & Download -------------------------------
|
159 |
-
st.header("3️⃣ Generate & Download PDF")
|
160 |
-
|
161 |
-
def build_timestamp(prefix_time=False):
|
162 |
-
fmt = "%Y-%m%d-%I%M%p" if prefix_time else "%Y-%m%d"
|
163 |
-
return datetime.now().strftime(fmt)
|
164 |
-
|
165 |
-
if st.button("🎉 Generate Full-Page PDF"):
|
166 |
if not ordered_files:
|
167 |
st.warning("Upload and reorder at least one image.")
|
168 |
else:
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
|
|
|
|
|
|
174 |
st.success(f"✅ PDF ready: **{fname}**")
|
175 |
-
st.download_button(
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
pix = doc[0].get_pixmap(matrix=fitz.Matrix(1.5,1.5))
|
181 |
-
st.image(pix.tobytes(), use_container_width=True)
|
182 |
-
except:
|
183 |
-
st.info("Install `pymupdf` for preview.")
|
184 |
-
|
185 |
-
# Custom-sized + captions button
|
186 |
-
if st.button("🖋️ Generate Image-Sized PDF with Captions"):
|
187 |
-
if not ordered_files:
|
188 |
-
st.warning("Upload and reorder at least one image.")
|
189 |
-
else:
|
190 |
-
date_s = build_timestamp(prefix_time=True)
|
191 |
-
words = first_n_words_ordered([f.name for f in ordered_files])
|
192 |
-
slug = "-".join(words)
|
193 |
-
fname = f"{date_s}-{slug}.pdf"
|
194 |
-
pdf = make_image_sized_pdf(ordered_files)
|
195 |
-
st.success(f"✅ PDF ready: **{fname}**")
|
196 |
-
st.download_button("⬇️ Download PDF", data=pdf, file_name=fname, mime="application/pdf")
|
197 |
-
st.markdown("#### Preview")
|
198 |
try:
|
199 |
import fitz
|
200 |
-
doc = fitz.open(stream=
|
201 |
-
pix = doc
|
202 |
st.image(pix.tobytes(), use_container_width=True)
|
203 |
-
except:
|
204 |
-
st.info("Install `pymupdf` for preview.")
|
205 |
|
206 |
# --- Footer ------------------------------------------------
|
207 |
st.sidebar.markdown("---")
|
|
|
1 |
import io
|
2 |
import os
|
|
|
3 |
import re
|
|
|
4 |
from datetime import datetime
|
5 |
+
from collections import Counter
|
6 |
|
7 |
import pandas as pd
|
8 |
import streamlit as st
|
|
|
19 |
|
20 |
st.title("🖼️ Image → PDF • Full-Page & Custom Layout Generator")
|
21 |
st.markdown(
|
22 |
+
"Upload images, filter by orientation, reorder visually, and generate a captioned PDF where each page matches its image's dimensions."
|
23 |
)
|
24 |
|
25 |
# --- Sidebar: Page Settings -----------------------------
|
|
|
44 |
)
|
45 |
page_width = BASE_WIDTH_PT
|
46 |
page_height = int(BASE_WIDTH_PT * (rh / rw))
|
47 |
+
st.sidebar.markdown(f"**Preview page size:** {page_width}×{page_height} pt")
|
48 |
|
49 |
# --- Main: Upload, Filter & Reorder -------------------
|
50 |
st.header("2️⃣ Upload, Filter & Reorder Images")
|
|
|
65 |
"height": h,
|
66 |
"aspect_ratio": ar,
|
67 |
"orientation": orient,
|
68 |
+
"order": idx,
|
69 |
})
|
70 |
df = pd.DataFrame(records)
|
71 |
dims = st.sidebar.multiselect(
|
|
|
73 |
default=["Landscape","Portrait","Square"]
|
74 |
)
|
75 |
df = df[df["orientation"].isin(dims)].reset_index(drop=True)
|
76 |
+
|
77 |
+
st.markdown("#### Image Metadata & Order")
|
78 |
st.dataframe(df.style.format({"aspect_ratio": "{:.2f}"}), use_container_width=True)
|
79 |
+
st.markdown("*Drag rows or edit the `order` column to set PDF page sequence.*")
|
80 |
try:
|
81 |
edited = st.experimental_data_editor(df, num_rows="fixed", use_container_width=True)
|
82 |
ordered_df = edited
|
|
|
92 |
use_container_width=True,
|
93 |
)
|
94 |
ordered_df = edited.sort_values("order").reset_index(drop=True)
|
95 |
+
|
96 |
name2file = {f.name: f for f in uploaded}
|
97 |
ordered_files = [name2file[n] for n in ordered_df["filename"] if n in name2file]
|
98 |
|
99 |
+
# --- Utility: Clean stems -------------------------------
|
100 |
+
def clean_stem(fn: str) -> str:
|
101 |
+
stem = os.path.splitext(fn)[0]
|
102 |
+
return stem.replace("-", " ").replace("_", " ")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
|
104 |
# --- PDF Creation: Image-sized + Captions --------------
|
105 |
def make_image_sized_pdf(images):
|
106 |
+
buffer = io.BytesIO()
|
107 |
+
c = canvas.Canvas(buffer)
|
108 |
+
for idx, f in enumerate(images, start=1):
|
109 |
im = Image.open(f)
|
110 |
iw, ih = im.size
|
111 |
+
# Caption height
|
112 |
cap_h = 20
|
113 |
page_w, page_h = iw, ih + cap_h
|
114 |
c.setPageSize((page_w, page_h))
|
115 |
+
# Draw image
|
116 |
c.drawImage(ImageReader(im), 0, cap_h, iw, ih, preserveAspectRatio=True, mask='auto')
|
117 |
+
# Draw caption
|
118 |
+
caption = clean_stem(f.name)
|
119 |
c.setFont("Helvetica", 12)
|
120 |
c.drawCentredString(page_w/2, cap_h/2, caption)
|
121 |
+
# Page number
|
122 |
+
c.setFont("Helvetica", 8)
|
123 |
+
c.drawRightString(page_w - 10, 10, str(idx))
|
124 |
c.showPage()
|
125 |
+
c.save()
|
126 |
+
buffer.seek(0)
|
127 |
+
return buffer.getvalue()
|
128 |
|
129 |
# --- Generate & Download -------------------------------
|
130 |
+
st.header("3️⃣ Generate & Download PDF with Captions")
|
131 |
+
if st.button("🖋️ Generate Captioned PDF"):
|
|
|
|
|
|
|
|
|
|
|
132 |
if not ordered_files:
|
133 |
st.warning("Upload and reorder at least one image.")
|
134 |
else:
|
135 |
+
# Timestamp + weekday
|
136 |
+
now = datetime.now()
|
137 |
+
prefix = now.strftime("%Y-%m%d-%I%M%p") + "-" + now.strftime("%a").upper()
|
138 |
+
# Build filename from ordered stems
|
139 |
+
stems = [clean_stem(f.name) for f in ordered_files]
|
140 |
+
basename = " - ".join(stems)
|
141 |
+
fname = f"{prefix}-{basename}.pdf"
|
142 |
+
pdf_bytes = make_image_sized_pdf(ordered_files)
|
143 |
st.success(f"✅ PDF ready: **{fname}**")
|
144 |
+
st.download_button(
|
145 |
+
"⬇️ Download PDF", data=pdf_bytes,
|
146 |
+
file_name=fname, mime="application/pdf"
|
147 |
+
)
|
148 |
+
st.markdown("#### Preview of Page 1")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
149 |
try:
|
150 |
import fitz
|
151 |
+
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
152 |
+
pix = doc.load_page(0).get_pixmap(matrix=fitz.Matrix(1.5,1.5))
|
153 |
st.image(pix.tobytes(), use_container_width=True)
|
154 |
+
except Exception:
|
155 |
+
st.info("Install `pymupdf` (`fitz`) for preview.")
|
156 |
|
157 |
# --- Footer ------------------------------------------------
|
158 |
st.sidebar.markdown("---")
|