awacke1 commited on
Commit
98946ea
Β·
verified Β·
1 Parent(s): 5e4c3ce

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -27
app.py CHANGED
@@ -9,26 +9,34 @@ from io import BytesIO
9
  import base64
10
  from imutils.video import VideoStream
11
  import cv2
 
 
 
 
12
 
13
- # 🌟πŸ”₯ Initialize session state like a galactic DJ spinning tracks!
14
  if 'file_history' not in st.session_state:
15
  st.session_state['file_history'] = []
16
  if 'auto_capture_running' not in st.session_state:
17
  st.session_state['auto_capture_running'] = False
18
 
19
- # πŸ“œπŸ’Ύ Save to history like a time-traveling scribe!
20
- def save_to_history(file_type, file_path, img_data):
21
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
22
- # Convert RGB to BGR for OpenCV saving
23
- img_bgr = cv2.cvtColor(img_data, cv2.COLOR_RGB2BGR)
24
- cv2.imwrite(file_path, img_bgr)
 
 
 
 
25
  st.session_state['file_history'].append({
26
  "Timestamp": timestamp,
27
  "Type": file_type,
28
  "Path": file_path
29
  })
30
 
31
- # πŸ“Έβ° Auto-capture every 10 secs like a sneaky shutterbug!
32
  def auto_capture(streams):
33
  while st.session_state['auto_capture_running']:
34
  for i, stream in enumerate(streams):
@@ -38,7 +46,7 @@ def auto_capture(streams):
38
  save_to_history("πŸ–ΌοΈ Image", filename, frame)
39
  time.sleep(10)
40
 
41
- # πŸŽ›οΈ Sidebar config like a spaceship control panel!
42
  with st.sidebar:
43
  st.header("πŸŽšοΈπŸ“Έ Snap Shack")
44
  streams = [
@@ -51,21 +59,36 @@ with st.sidebar:
51
  if st.button("⏹️ Stop Auto-Snap"):
52
  st.session_state['auto_capture_running'] = False
53
 
54
- # πŸ“‚ Sidebar file outline with emoji flair!
 
 
 
 
 
55
  st.subheader("πŸ“œ Snap Stash")
56
  if st.session_state['file_history']:
57
  images = [f for f in st.session_state['file_history'] if f['Type'] == "πŸ–ΌοΈ Image"]
 
 
58
  if images:
59
  st.write("πŸ–ΌοΈ Images")
60
  for img in images:
61
  st.write(f"- {img['Path']} @ {img['Timestamp']}")
 
 
 
 
 
 
 
 
62
  else:
63
  st.write("πŸ•³οΈ Empty Stash!")
64
 
65
- # 🌍🎨 Main UI kicks off like a cosmic art show!
66
- st.title("πŸ“Έ Imutils Snap Craze")
67
 
68
- # πŸ“ΈπŸ“· Camera snap zone!
69
  st.header("πŸ“ΈπŸŽ₯ Snap Zone")
70
  cols = st.columns(2)
71
  placeholders = [cols[0].empty(), cols[1].empty()]
@@ -74,31 +97,37 @@ for i, (placeholder, stream) in enumerate(zip(placeholders, streams)):
74
  if frame is not None:
75
  placeholder.image(frame, caption=f"Live Cam {i}", use_container_width=True)
76
  else:
77
- placeholder.error(f"🚨 No feed from Cam {i}. Check connection or index.")
78
 
79
  if st.button(f"πŸ“Έ Snap Cam {i}", key=f"snap{i}"):
80
  frame = stream.read()
81
  if frame is not None:
82
  filename = f"cam{i}_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
83
  save_to_history("πŸ–ΌοΈ Image", filename, frame)
84
- else:
85
- st.error(f"🚨 Failed to snap Cam {i}")
86
 
87
- # πŸ“‚ Upload zone like a media drop party!
88
  st.header("πŸ“₯πŸŽ‰ Drop Zone")
89
- uploaded_files = st.file_uploader("πŸ“Έ Toss Pics", accept_multiple_files=True, type=['jpg', 'png'])
90
  if uploaded_files:
91
  for uploaded_file in uploaded_files:
92
- file_path = f"uploaded_{uploaded_file.name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
93
- img = Image.open(uploaded_file)
94
- img_array = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) # Convert for consistency
95
- save_to_history("πŸ–ΌοΈ Image", file_path, img_array)
96
- st.image(img, caption=uploaded_file.name, use_container_width=True)
 
 
 
 
 
 
97
 
98
- # πŸ–ΌοΈ Gallery like a media circus!
99
  st.header("πŸŽͺ Snap Show")
100
  if st.session_state['file_history']:
101
  images = [f for f in st.session_state['file_history'] if f['Type'] == "πŸ–ΌοΈ Image"]
 
 
102
  if images:
103
  st.subheader("πŸ–ΌοΈ Pic Parade")
104
  cols = st.columns(3)
@@ -109,12 +138,25 @@ if st.session_state['file_history']:
109
  with open(img['Path'], "rb") as f:
110
  img_data = f.read()
111
  st.markdown(f'<a href="data:image/jpeg;base64,{base64.b64encode(img_data).decode()}" download="{os.path.basename(img["Path"])}">πŸ“₯ Snag It!</a>', unsafe_allow_html=True)
112
- else:
113
- st.warning(f"🚨 Missing file: {img['Path']}")
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  else:
115
  st.write("🚫 No snaps yet!")
116
 
117
- # πŸ“œ History log like a time machine!
118
  st.header("⏳ Snap Saga")
119
  if st.session_state['file_history']:
120
  df = pd.DataFrame(st.session_state['file_history'])
@@ -122,7 +164,7 @@ if st.session_state['file_history']:
122
  else:
123
  st.write("πŸ•³οΈ Nothing snapped yet!")
124
 
125
- # Cleanup on app exit
126
  def cleanup():
127
  for stream in streams:
128
  stream.stop()
 
9
  import base64
10
  from imutils.video import VideoStream
11
  import cv2
12
+ from pydub import AudioSegment
13
+ from pydub.playback import play
14
+ import pypdf
15
+ import numpy as np
16
 
17
+ # 🌟πŸ”₯ Initialize session state
18
  if 'file_history' not in st.session_state:
19
  st.session_state['file_history'] = []
20
  if 'auto_capture_running' not in st.session_state:
21
  st.session_state['auto_capture_running'] = False
22
 
23
+ # πŸ“œπŸ’Ύ Save to history
24
+ def save_to_history(file_type, file_path, data=None):
25
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
26
+ if file_type == "πŸ–ΌοΈ Image" and data is not None:
27
+ cv2.imwrite(file_path, cv2.cvtColor(data, cv2.COLOR_RGB2BGR))
28
+ elif file_type == "🎡 Audio" and data is not None:
29
+ data.export(file_path, format="wav")
30
+ elif file_type == "πŸ“œ PDF" and data is not None:
31
+ with open(file_path, "wb") as f:
32
+ f.write(data)
33
  st.session_state['file_history'].append({
34
  "Timestamp": timestamp,
35
  "Type": file_type,
36
  "Path": file_path
37
  })
38
 
39
+ # πŸ“Έβ° Auto-capture every 10 secs
40
  def auto_capture(streams):
41
  while st.session_state['auto_capture_running']:
42
  for i, stream in enumerate(streams):
 
46
  save_to_history("πŸ–ΌοΈ Image", filename, frame)
47
  time.sleep(10)
48
 
49
+ # πŸŽ›οΈ Sidebar config
50
  with st.sidebar:
51
  st.header("πŸŽšοΈπŸ“Έ Snap Shack")
52
  streams = [
 
59
  if st.button("⏹️ Stop Auto-Snap"):
60
  st.session_state['auto_capture_running'] = False
61
 
62
+ # Audio recording control
63
+ if st.button("πŸŽ™οΈ Record Audio (5s)"):
64
+ audio = AudioSegment.silent(duration=5000) # Placeholder; real mic capture needs pyaudio
65
+ filename = f"audio_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
66
+ save_to_history("🎡 Audio", filename, audio)
67
+
68
  st.subheader("πŸ“œ Snap Stash")
69
  if st.session_state['file_history']:
70
  images = [f for f in st.session_state['file_history'] if f['Type'] == "πŸ–ΌοΈ Image"]
71
+ audios = [f for f in st.session_state['file_history'] if f['Type'] == "🎡 Audio"]
72
+ pdfs = [f for f in st.session_state['file_history'] if f['Type'] == "πŸ“œ PDF"]
73
  if images:
74
  st.write("πŸ–ΌοΈ Images")
75
  for img in images:
76
  st.write(f"- {img['Path']} @ {img['Timestamp']}")
77
+ if audios:
78
+ st.write("🎡 Audios")
79
+ for aud in audios:
80
+ st.write(f"- {aud['Path']} @ {aud['Timestamp']}")
81
+ if pdfs:
82
+ st.write("πŸ“œ PDFs")
83
+ for pdf in pdfs:
84
+ st.write(f"- {pdf['Path']} @ {pdf['Timestamp']}")
85
  else:
86
  st.write("πŸ•³οΈ Empty Stash!")
87
 
88
+ # 🌍🎨 Main UI
89
+ st.title("πŸ“Έ Multi-Lib Snap Craze")
90
 
91
+ # πŸ“ΈπŸ“· Camera snap zone
92
  st.header("πŸ“ΈπŸŽ₯ Snap Zone")
93
  cols = st.columns(2)
94
  placeholders = [cols[0].empty(), cols[1].empty()]
 
97
  if frame is not None:
98
  placeholder.image(frame, caption=f"Live Cam {i}", use_container_width=True)
99
  else:
100
+ placeholder.error(f"🚨 No feed from Cam {i}")
101
 
102
  if st.button(f"πŸ“Έ Snap Cam {i}", key=f"snap{i}"):
103
  frame = stream.read()
104
  if frame is not None:
105
  filename = f"cam{i}_snap_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
106
  save_to_history("πŸ–ΌοΈ Image", filename, frame)
 
 
107
 
108
+ # πŸ“‚ Upload zone (PDFs and Images)
109
  st.header("πŸ“₯πŸŽ‰ Drop Zone")
110
+ uploaded_files = st.file_uploader("πŸ“œπŸ“Έ Upload PDFs or Images", accept_multiple_files=True, type=['pdf', 'jpg', 'png'])
111
  if uploaded_files:
112
  for uploaded_file in uploaded_files:
113
+ file_type = "πŸ“œ PDF" if uploaded_file.type == "application/pdf" else "πŸ–ΌοΈ Image"
114
+ file_path = f"uploaded_{uploaded_file.name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.{uploaded_file.name.split('.')[-1]}"
115
+ if file_type == "πŸ–ΌοΈ Image":
116
+ img = Image.open(uploaded_file)
117
+ img_array = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
118
+ save_to_history(file_type, file_path, img_array)
119
+ st.image(img, caption=uploaded_file.name, use_container_width=True)
120
+ else:
121
+ save_to_history(file_type, file_path, uploaded_file.getvalue())
122
+ with pypdf.PdfReader(uploaded_file) as reader:
123
+ st.write(f"PDF Pages: {len(reader.pages)}")
124
 
125
+ # πŸ–ΌοΈ Gallery
126
  st.header("πŸŽͺ Snap Show")
127
  if st.session_state['file_history']:
128
  images = [f for f in st.session_state['file_history'] if f['Type'] == "πŸ–ΌοΈ Image"]
129
+ audios = [f for f in st.session_state['file_history'] if f['Type'] == "🎡 Audio"]
130
+ pdfs = [f for f in st.session_state['file_history'] if f['Type'] == "πŸ“œ PDF"]
131
  if images:
132
  st.subheader("πŸ–ΌοΈ Pic Parade")
133
  cols = st.columns(3)
 
138
  with open(img['Path'], "rb") as f:
139
  img_data = f.read()
140
  st.markdown(f'<a href="data:image/jpeg;base64,{base64.b64encode(img_data).decode()}" download="{os.path.basename(img["Path"])}">πŸ“₯ Snag It!</a>', unsafe_allow_html=True)
141
+ if audios:
142
+ st.subheader("🎡 Audio Alley")
143
+ for aud in audios:
144
+ if os.path.exists(aud['Path']):
145
+ st.audio(aud['Path'])
146
+ with open(aud['Path'], "rb") as f:
147
+ aud_data = f.read()
148
+ st.markdown(f'<a href="data:audio/wav;base64,{base64.b64encode(aud_data).decode()}" download="{os.path.basename(aud["Path"])}">πŸ“₯ Snag It!</a>', unsafe_allow_html=True)
149
+ if pdfs:
150
+ st.subheader("πŸ“œ PDF Plaza")
151
+ for pdf in pdfs:
152
+ if os.path.exists(pdf['Path']):
153
+ with open(pdf['Path'], "rb") as f:
154
+ pdf_data = f.read()
155
+ st.markdown(f'<a href="data:application/pdf;base64,{base64.b64encode(pdf_data).decode()}" download="{os.path.basename(pdf["Path"])}">πŸ“₯ Download {os.path.basename(pdf["Path"])}</a>', unsafe_allow_html=True)
156
  else:
157
  st.write("🚫 No snaps yet!")
158
 
159
+ # πŸ“œ History log
160
  st.header("⏳ Snap Saga")
161
  if st.session_state['file_history']:
162
  df = pd.DataFrame(st.session_state['file_history'])
 
164
  else:
165
  st.write("πŸ•³οΈ Nothing snapped yet!")
166
 
167
+ # Cleanup
168
  def cleanup():
169
  for stream in streams:
170
  stream.stop()