awacke1 commited on
Commit
7dd1eae
·
verified ·
1 Parent(s): 2a632c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -40
app.py CHANGED
@@ -8,8 +8,8 @@ import pikepdf
8
  import fpdf
9
  import fitz # pymupdf
10
  import cv2
 
11
  from PIL import Image
12
- import imutils.video
13
  import io
14
  import os
15
 
@@ -31,14 +31,21 @@ ml_outline = [
31
 
32
  # Demo functions for PDF libraries
33
  def demo_pikepdf():
 
34
  pdf = pikepdf.Pdf.new()
35
- pdf.pages.append(pikepdf.Page(pikepdf.Dictionary()))
 
 
 
 
 
36
  buffer = io.BytesIO()
37
  pdf.save(buffer)
38
  buffer.seek(0)
39
  return buffer.getvalue()
40
 
41
  def demo_fpdf():
 
42
  pdf = fpdf.FPDF()
43
  pdf.add_page()
44
  pdf.set_font("Arial", size=12)
@@ -49,6 +56,7 @@ def demo_fpdf():
49
  return buffer.getvalue()
50
 
51
  def demo_pymupdf():
 
52
  doc = fitz.open()
53
  page = doc.new_page()
54
  page.insert_text((100, 100), "PyMuPDF Demo")
@@ -57,26 +65,44 @@ def demo_pymupdf():
57
  buffer.seek(0)
58
  return buffer.getvalue()
59
 
60
- # Demo function for image capture (using OpenCV as representative)
61
  def demo_image_capture():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  try:
63
- cap = cv2.VideoCapture(0)
64
- ret, frame = cap.read()
65
- if ret:
66
- rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
67
- img = Image.fromarray(rgb_frame)
68
- buffer = io.BytesIO()
69
- img.save(buffer, format="JPEG")
70
- buffer.seek(0)
71
- cap.release()
72
- return buffer.getvalue()
73
- cap.release()
74
  except:
75
- return None
76
- return None
 
 
 
 
 
 
 
77
 
78
  # Main PDF creation using ReportLab
79
  def create_main_pdf(outline_items):
 
80
  buffer = io.BytesIO()
81
  doc = SimpleDocTemplate(buffer, pagesize=(A4[1], A4[0])) # Landscape
82
  styles = getSampleStyleSheet()
@@ -88,7 +114,7 @@ def create_main_pdf(outline_items):
88
 
89
  # Normal style
90
  normal_style = styles['Normal']
91
- normal_style.fontSize = 10
92
  normal_style.leading = 14
93
 
94
  # Page 1: Items 1-6
@@ -113,6 +139,7 @@ def create_main_pdf(outline_items):
113
  return buffer.getvalue()
114
 
115
  def get_binary_file_downloader_html(bin_data, file_label='File'):
 
116
  bin_str = base64.b64encode(bin_data).decode()
117
  href = f'<a href="data:application/octet-stream;base64,{bin_str}" download="{file_label}">Download {file_label}</a>'
118
  return href
@@ -127,46 +154,54 @@ with col1:
127
  outline_text = "\n".join(ml_outline)
128
  st.markdown(outline_text)
129
 
130
- md_file = "ml_outline.md"
131
- with open(md_file, "w", encoding='utf-8') as f:
132
- f.write(outline_text)
133
- st.markdown(get_binary_file_downloader_html(outline_text.encode('utf-8'), "ml_outline.md"), unsafe_allow_html=True)
 
 
 
134
 
135
  with col2:
136
  st.header("📑 PDF Preview & Demos")
137
 
138
  # Library Demos
139
  st.subheader("Library Demos")
140
- if st.button("Run PDF Demos"):
141
  with st.spinner("Running demos..."):
142
- # pikepdf demo
143
- pike_pdf = demo_pikepdf()
144
- st.download_button("Download pikepdf Demo", pike_pdf, "pikepdf_demo.pdf")
145
 
146
- # fpdf demo
147
- fpdf_pdf = demo_fpdf()
148
- st.download_button("Download fpdf Demo", fpdf_pdf, "fpdf_demo.pdf")
 
 
149
 
150
- # pymupdf demo
151
- pymupdf_pdf = demo_pymupdf()
152
- st.download_button("Download pymupdf Demo", pymupdf_pdf, "pymupdf_demo.pdf")
 
 
153
 
154
- # Image capture demo
155
- img_data = demo_image_capture()
156
- if img_data:
157
- st.image(img_data, caption="OpenCV Image Capture Demo")
158
- else:
159
- st.warning("Image capture demo failed - camera not detected")
 
 
 
 
160
 
161
  # Main PDF Generation
 
162
  if st.button("Generate Main PDF"):
163
  with st.spinner("Generating PDF..."):
164
  try:
165
  pdf_bytes = create_main_pdf(ml_outline)
166
 
167
- with open("ml_outline.pdf", "wb") as f:
168
- f.write(pdf_bytes)
169
-
170
  st.download_button(
171
  label="Download Main PDF",
172
  data=pdf_bytes,
@@ -174,6 +209,7 @@ with col2:
174
  mime="application/pdf"
175
  )
176
 
 
177
  base64_pdf = base64.b64encode(pdf_bytes).decode('utf-8')
178
  pdf_display = f'''
179
  <embed
@@ -183,14 +219,30 @@ with col2:
183
  type="application/pdf">
184
  '''
185
  st.markdown(pdf_display, unsafe_allow_html=True)
 
 
186
  except Exception as e:
187
  st.error(f"Error generating PDF: {str(e)}")
188
 
 
189
  st.markdown("""
190
  <style>
191
  .stButton>button {
192
  background-color: #4CAF50;
193
  color: white;
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  }
195
  </style>
196
  """, unsafe_allow_html=True)
 
8
  import fpdf
9
  import fitz # pymupdf
10
  import cv2
11
+ import numpy as np
12
  from PIL import Image
 
13
  import io
14
  import os
15
 
 
31
 
32
  # Demo functions for PDF libraries
33
  def demo_pikepdf():
34
+ """Create a simple PDF with pikepdf"""
35
  pdf = pikepdf.Pdf.new()
36
+ page = pdf.make_indirect(pikepdf.Dictionary(
37
+ Type=pikepdf.Name.Page,
38
+ MediaBox=[0, 0, 595, 842],
39
+ Contents=pdf.make_stream(b"BT /F1 12 Tf 100 700 Td (PikePDF Demo) Tj ET")
40
+ ))
41
+ pdf.pages.append(page)
42
  buffer = io.BytesIO()
43
  pdf.save(buffer)
44
  buffer.seek(0)
45
  return buffer.getvalue()
46
 
47
  def demo_fpdf():
48
+ """Create a simple PDF with fpdf"""
49
  pdf = fpdf.FPDF()
50
  pdf.add_page()
51
  pdf.set_font("Arial", size=12)
 
56
  return buffer.getvalue()
57
 
58
  def demo_pymupdf():
59
+ """Create a simple PDF with pymupdf"""
60
  doc = fitz.open()
61
  page = doc.new_page()
62
  page.insert_text((100, 100), "PyMuPDF Demo")
 
65
  buffer.seek(0)
66
  return buffer.getvalue()
67
 
68
+ # Demo function for image capture
69
  def demo_image_capture():
70
+ """Generate a demo image (fake capture) since we can't access the camera in this environment"""
71
+ # Create a simple gradient image using numpy and PIL
72
+ width, height = 640, 480
73
+
74
+ # Create a gradient array
75
+ x = np.linspace(0, 1, width)
76
+ y = np.linspace(0, 1, height)
77
+ xx, yy = np.meshgrid(x, y)
78
+ gradient = (xx + yy) / 2
79
+
80
+ # Convert to RGB image
81
+ img_array = (gradient * 255).astype(np.uint8)
82
+ rgb_array = np.stack([img_array, img_array//2, img_array*2], axis=2)
83
+
84
+ # Create PIL Image
85
+ img = Image.fromarray(rgb_array)
86
+
87
+ # Add text to the image
88
+ from PIL import ImageDraw, ImageFont
89
+ draw = ImageDraw.Draw(img)
90
  try:
91
+ font = ImageFont.truetype("arial.ttf", 30)
 
 
 
 
 
 
 
 
 
 
92
  except:
93
+ font = ImageFont.load_default()
94
+
95
+ draw.text((width//4, height//2), "OpenCV Demo Image", fill=(255, 255, 255), font=font)
96
+
97
+ # Save to buffer
98
+ buffer = io.BytesIO()
99
+ img.save(buffer, format="JPEG")
100
+ buffer.seek(0)
101
+ return buffer.getvalue()
102
 
103
  # Main PDF creation using ReportLab
104
  def create_main_pdf(outline_items):
105
+ """Create a two-page landscape PDF with the outline split between pages"""
106
  buffer = io.BytesIO()
107
  doc = SimpleDocTemplate(buffer, pagesize=(A4[1], A4[0])) # Landscape
108
  styles = getSampleStyleSheet()
 
114
 
115
  # Normal style
116
  normal_style = styles['Normal']
117
+ normal_style.fontSize = 12
118
  normal_style.leading = 14
119
 
120
  # Page 1: Items 1-6
 
139
  return buffer.getvalue()
140
 
141
  def get_binary_file_downloader_html(bin_data, file_label='File'):
142
+ """Create a download link for binary data"""
143
  bin_str = base64.b64encode(bin_data).decode()
144
  href = f'<a href="data:application/octet-stream;base64,{bin_str}" download="{file_label}">Download {file_label}</a>'
145
  return href
 
154
  outline_text = "\n".join(ml_outline)
155
  st.markdown(outline_text)
156
 
157
+ # Create a download button for the markdown file
158
+ st.download_button(
159
+ label="Download Markdown",
160
+ data=outline_text,
161
+ file_name="ml_outline.md",
162
+ mime="text/markdown"
163
+ )
164
 
165
  with col2:
166
  st.header("📑 PDF Preview & Demos")
167
 
168
  # Library Demos
169
  st.subheader("Library Demos")
170
+ if st.button("Run PDF Library Demos"):
171
  with st.spinner("Running demos..."):
172
+ # Create tabs for each demo
173
+ demo_tabs = st.tabs(["PikePDF", "FPDF", "PyMuPDF", "Image Demo"])
 
174
 
175
+ with demo_tabs[0]:
176
+ # pikepdf demo
177
+ pike_pdf = demo_pikepdf()
178
+ st.download_button("Download pikepdf Demo", pike_pdf, "pikepdf_demo.pdf")
179
+ st.write("PikePDF demo created successfully!")
180
 
181
+ with demo_tabs[1]:
182
+ # fpdf demo
183
+ fpdf_pdf = demo_fpdf()
184
+ st.download_button("Download fpdf Demo", fpdf_pdf, "fpdf_demo.pdf")
185
+ st.write("FPDF demo created successfully!")
186
 
187
+ with demo_tabs[2]:
188
+ # pymupdf demo
189
+ pymupdf_pdf = demo_pymupdf()
190
+ st.download_button("Download pymupdf Demo", pymupdf_pdf, "pymupdf_demo.pdf")
191
+ st.write("PyMuPDF demo created successfully!")
192
+
193
+ with demo_tabs[3]:
194
+ # Image demo
195
+ img_data = demo_image_capture()
196
+ st.image(img_data, caption="Demo Image (Camera simulation)")
197
 
198
  # Main PDF Generation
199
+ st.subheader("Main Outline PDF")
200
  if st.button("Generate Main PDF"):
201
  with st.spinner("Generating PDF..."):
202
  try:
203
  pdf_bytes = create_main_pdf(ml_outline)
204
 
 
 
 
205
  st.download_button(
206
  label="Download Main PDF",
207
  data=pdf_bytes,
 
209
  mime="application/pdf"
210
  )
211
 
212
+ # Display the PDF in the app
213
  base64_pdf = base64.b64encode(pdf_bytes).decode('utf-8')
214
  pdf_display = f'''
215
  <embed
 
219
  type="application/pdf">
220
  '''
221
  st.markdown(pdf_display, unsafe_allow_html=True)
222
+
223
+ st.success("PDF generated successfully! You can view it above and download it using the button.")
224
  except Exception as e:
225
  st.error(f"Error generating PDF: {str(e)}")
226
 
227
+ # Add custom CSS for better appearance
228
  st.markdown("""
229
  <style>
230
  .stButton>button {
231
  background-color: #4CAF50;
232
  color: white;
233
+ font-weight: bold;
234
+ }
235
+ .stTabs [data-baseweb="tab-list"] {
236
+ gap: 2px;
237
+ }
238
+ .stTabs [data-baseweb="tab"] {
239
+ height: 50px;
240
+ white-space: pre-wrap;
241
+ background-color: #f0f2f6;
242
+ border-radius: 4px 4px 0px 0px;
243
+ gap: 1px;
244
+ padding-top: 10px;
245
+ padding-bottom: 10px;
246
  }
247
  </style>
248
  """, unsafe_allow_html=True)