awacke1 commited on
Commit
3cbf6c1
ยท
verified ยท
1 Parent(s): 486d5d2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +324 -0
app.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from datetime import datetime
4
+ import cv2
5
+ import pyaudio
6
+ import wave
7
+ import imageio
8
+ import av
9
+ import moviepy.editor as mp
10
+ import os
11
+ import numpy as np
12
+ from io import BytesIO
13
+
14
+ # Initialize session state
15
+ if 'file_history' not in st.session_state:
16
+ st.session_state['file_history'] = []
17
+ if 'ping_code' not in st.session_state:
18
+ st.session_state['ping_code'] = ""
19
+ if 'uploaded_files' not in st.session_state:
20
+ st.session_state['uploaded_files'] = []
21
+
22
+ # Function to save to history
23
+ def save_to_history(file_type, file_path):
24
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
25
+ st.session_state['file_history'].append({
26
+ "Timestamp": timestamp,
27
+ "Type": file_type,
28
+ "Path": file_path
29
+ })
30
+
31
+ # Sidebar configuration
32
+ st.sidebar.header("๐Ÿ“ธ Configuration")
33
+ library_choice = st.sidebar.selectbox(
34
+ "Select Library",
35
+ ["OpenCV", "PyAudio", "ImageIO", "PyAV", "MoviePy"]
36
+ )
37
+ resolution = st.sidebar.select_slider(
38
+ "Resolution",
39
+ options=["320x240", "640x480", "1280x720"],
40
+ value="640x480"
41
+ )
42
+ fps = st.sidebar.slider("FPS", 1, 60, 30)
43
+
44
+ # DTMF-style ping code input
45
+ st.sidebar.subheader("๐Ÿ”ข Device Ping Code")
46
+ col1, col2, col3, col4 = st.sidebar.columns(4)
47
+ with col1:
48
+ digit1 = st.selectbox("D1", [str(i) for i in range(10)], key="d1")
49
+ with col2:
50
+ digit2 = st.selectbox("D2", [str(i) for i in range(10)], key="d2")
51
+ with col3:
52
+ digit3 = st.selectbox("D3", [str(i) for i in range(10)], key="d3")
53
+ with col4:
54
+ digit4 = st.selectbox("D4", [str(i) for i in range(10)], key="d4")
55
+ ping_code = digit1 + digit2 + digit3 + digit4
56
+ st.session_state['ping_code'] = ping_code
57
+ st.sidebar.write(f"Ping Code: {ping_code}")
58
+
59
+ # Main UI
60
+ st.title("๐Ÿ“ธ Camera & Audio Capture Tool")
61
+
62
+ # Outline with top 3 function examples
63
+ st.header("๐Ÿ“ธ Top Five Python Libraries")
64
+
65
+ # 1. OpenCV
66
+ with st.expander("1. ๐Ÿ“ท OpenCV"):
67
+ st.write("๐ŸŽฅ *Best Feature*: Real-time image processing and video capture.")
68
+ st.subheader("Top 3 Function Examples")
69
+
70
+ st.write("1. `cv2.VideoCapture()` - Capture and display video")
71
+ if st.button("Run VideoCapture", key="opencv_1"):
72
+ cap = cv2.VideoCapture(0)
73
+ frame_placeholder = st.empty()
74
+ for _ in range(50): # 50 frames
75
+ ret, frame = cap.read()
76
+ if ret:
77
+ frame_placeholder.image(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
78
+ cap.release()
79
+
80
+ st.write("2. `cv2.imwrite()` - Save processed image")
81
+ if st.button("Run imwrite", key="opencv_2"):
82
+ cap = cv2.VideoCapture(0)
83
+ ret, frame = cap.read()
84
+ if ret:
85
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Convert to grayscale
86
+ file_path = f"opencv_gray_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
87
+ cv2.imwrite(file_path, gray)
88
+ save_to_history("Image", file_path)
89
+ st.image(file_path, caption="Grayscale Image")
90
+ cap.release()
91
+
92
+ st.write("3. `cv2.Canny()` - Edge detection")
93
+ if st.button("Run Canny", key="opencv_3"):
94
+ cap = cv2.VideoCapture(0)
95
+ ret, frame = cap.read()
96
+ if ret:
97
+ edges = cv2.Canny(frame, 100, 200)
98
+ file_path = f"opencv_edges_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
99
+ cv2.imwrite(file_path, edges)
100
+ save_to_history("Image", file_path)
101
+ st.image(file_path, caption="Edge Detection")
102
+ cap.release()
103
+
104
+ # 2. PyAudio
105
+ with st.expander("2. ๐ŸŽ™๏ธ PyAudio"):
106
+ st.write("๐Ÿ”Š *Best Feature*: Low-level audio input/output control.")
107
+ st.subheader("Top 3 Function Examples")
108
+
109
+ st.write("1. `PyAudio.open()` - Record audio")
110
+ if st.button("Run Audio Record", key="pyaudio_1"):
111
+ p = pyaudio.PyAudio()
112
+ stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=1024)
113
+ frames = [stream.read(1024) for _ in range(int(44100 / 1024 * 3))] # 3 seconds
114
+ stream.stop_stream()
115
+ stream.close()
116
+ p.terminate()
117
+ file_path = f"pyaudio_rec_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
118
+ with wave.open(file_path, 'wb') as wf:
119
+ wf.setnchannels(1)
120
+ wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
121
+ wf.setframerate(44100)
122
+ wf.writeframes(b''.join(frames))
123
+ save_to_history("Audio", file_path)
124
+ st.audio(file_path)
125
+
126
+ st.write("2. `PyAudio.get_device_info_by_index()` - List audio devices")
127
+ if st.button("Run Device Info", key="pyaudio_2"):
128
+ p = pyaudio.PyAudio()
129
+ devices = [p.get_device_info_by_index(i) for i in range(p.get_device_count())]
130
+ st.write("Available Audio Devices:", devices)
131
+ p.terminate()
132
+
133
+ st.write("3. `stream.read()` - Real-time audio data")
134
+ if st.button("Run Stream Read", key="pyaudio_3"):
135
+ p = pyaudio.PyAudio()
136
+ stream = p.open(format=pyaudio.paInt16, channels=1, rate=44100, input=True, frames_per_buffer=1024)
137
+ data = stream.read(1024)
138
+ st.write("Sample audio data length:", len(data))
139
+ stream.stop_stream()
140
+ stream.close()
141
+ p.terminate()
142
+
143
+ # 3. ImageIO
144
+ with st.expander("3. ๐Ÿ“น ImageIO"):
145
+ st.write("๐ŸŽฅ *Best Feature*: Simple and efficient image/video I/O.")
146
+ st.subheader("Top 3 Function Examples")
147
+
148
+ st.write("1. `imageio.get_reader()` - Read webcam frames")
149
+ if st.button("Run get_reader", key="imageio_1"):
150
+ reader = imageio.get_reader('<video0>')
151
+ frame = reader.get_next_data()
152
+ file_path = f"imageio_frame_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
153
+ imageio.imwrite(file_path, frame)
154
+ save_to_history("Image", file_path)
155
+ st.image(file_path)
156
+
157
+ st.write("2. `imageio.imwrite()` - Save image with compression")
158
+ if st.button("Run imwrite", key="imageio_2"):
159
+ reader = imageio.get_reader('<video0>')
160
+ frame = reader.get_next_data()
161
+ file_path = f"imageio_comp_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
162
+ imageio.imwrite(file_path, frame, quality=85) # Compressed
163
+ save_to_history("Image", file_path)
164
+ st.image(file_path, caption="Compressed Image")
165
+
166
+ st.write("3. `imageio.mimwrite()` - Create GIF")
167
+ if st.button("Run mimwrite", key="imageio_3"):
168
+ reader = imageio.get_reader('<video0>')
169
+ frames = [reader.get_next_data() for _ in range(10)]
170
+ file_path = f"imageio_gif_{datetime.now().strftime('%Y%m%d_%H%M%S')}.gif"
171
+ imageio.mimwrite(file_path, frames, fps=5)
172
+ save_to_history("GIF", file_path)
173
+ st.image(file_path, caption="GIF")
174
+
175
+ # 4. PyAV
176
+ with st.expander("4. ๐ŸŽฌ PyAV"):
177
+ st.write("๐ŸŽฅ *Best Feature*: Powerful FFmpeg-based AV processing.")
178
+ st.subheader("Top 3 Function Examples")
179
+
180
+ st.write("1. `av.open()` - Capture video")
181
+ if st.button("Run av.open", key="pyav_1"):
182
+ container = av.open('/dev/video0')
183
+ stream = container.streams.video[0]
184
+ file_path = f"pyav_vid_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
185
+ output = av.open(file_path, 'w')
186
+ out_stream = output.add_stream('h264', rate=30)
187
+ for i, frame in enumerate(container.decode(stream)):
188
+ if i > 30: break
189
+ out_frame = frame.reformat(out_stream.width, out_stream.height)
190
+ output.mux(out_stream.encode(out_frame))
191
+ output.close()
192
+ container.close()
193
+ save_to_history("Video", file_path)
194
+ st.video(file_path)
195
+
196
+ st.write("2. `container.decode()` - Extract audio")
197
+ if st.button("Run decode", key="pyav_2"):
198
+ container = av.open('/dev/video0', 'r', format='v4l2')
199
+ file_path = f"pyav_audio_{datetime.now().strftime('%Y%m%d_%H%M%S')}.wav"
200
+ output = av.open(file_path, 'w')
201
+ out_stream = output.add_stream('pcm_s16le', rate=44100)
202
+ for packet in container.demux():
203
+ for frame in packet.decode():
204
+ if frame.is_corrupt: continue
205
+ if hasattr(frame, 'to_ndarray'):
206
+ output.mux(out_stream.encode(frame))
207
+ if os.path.getsize(file_path) > 100000: break # Limit size
208
+ output.close()
209
+ container.close()
210
+ save_to_history("Audio", file_path)
211
+ st.audio(file_path)
212
+
213
+ st.write("3. `av.filter()` - Apply video filter")
214
+ if st.button("Run filter", key="pyav_3"):
215
+ container = av.open('/dev/video0')
216
+ stream = container.streams.video[0]
217
+ file_path = f"pyav_filter_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
218
+ output = av.open(file_path, 'w')
219
+ out_stream = output.add_stream('h264', rate=30)
220
+ graph = av.filter.Graph()
221
+ filt = graph.add("negate") # Invert colors
222
+ for i, frame in enumerate(container.decode(stream)):
223
+ if i > 30: break
224
+ filt.push(frame)
225
+ out_frame = filt.pull()
226
+ output.mux(out_stream.encode(out_frame.reformat(out_stream.width, out_stream.height)))
227
+ output.close()
228
+ container.close()
229
+ save_to_history("Video", file_path)
230
+ st.video(file_path, caption="Negated Video")
231
+
232
+ # 5. MoviePy
233
+ with st.expander("5. ๐Ÿ“ผ MoviePy"):
234
+ st.write("๐ŸŽฅ *Best Feature*: High-level video editing.")
235
+ st.subheader("Top 3 Function Examples")
236
+
237
+ st.write("1. `ImageSequenceClip()` - Video from frames")
238
+ if st.button("Run ImageSequenceClip", key="moviepy_1"):
239
+ cap = cv2.VideoCapture(0)
240
+ frames = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(30)]
241
+ cap.release()
242
+ file_path = f"moviepy_seq_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
243
+ clip = mp.ImageSequenceClip(frames, fps=15)
244
+ clip.write_videofile(file_path)
245
+ save_to_history("Video", file_path)
246
+ st.video(file_path)
247
+
248
+ st.write("2. `VideoFileClip()` - Load and resize video")
249
+ if st.button("Run VideoFileClip", key="moviepy_2"):
250
+ cap = cv2.VideoCapture(0)
251
+ frames = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(30)]
252
+ cap.release()
253
+ temp_path = "temp.mp4"
254
+ mp.ImageSequenceClip(frames, fps=15).write_videofile(temp_path)
255
+ clip = mp.VideoFileClip(temp_path).resize((320, 240))
256
+ file_path = f"moviepy_resized_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
257
+ clip.write_videofile(file_path)
258
+ save_to_history("Video", file_path)
259
+ st.video(file_path, caption="Resized Video")
260
+
261
+ st.write("3. `concatenate_videoclips()` - Combine clips")
262
+ if st.button("Run concatenate", key="moviepy_3"):
263
+ cap = cv2.VideoCapture(0)
264
+ frames1 = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(15)]
265
+ frames2 = [cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB) for _ in range(15)]
266
+ cap.release()
267
+ clip1 = mp.ImageSequenceClip(frames1, fps=15)
268
+ clip2 = mp.ImageSequenceClip(frames2, fps=15)
269
+ final_clip = mp.concatenate_videoclips([clip1, clip2])
270
+ file_path = f"moviepy_concat_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
271
+ final_clip.write_videofile(file_path)
272
+ save_to_history("Video", file_path)
273
+ st.video(file_path, caption="Concatenated Video")
274
+
275
+ # Media Upload Section
276
+ st.header("๐Ÿ“‚ Upload Media Files")
277
+ uploaded_files = st.file_uploader("Upload Images, Audio, or Video", accept_multiple_files=True, type=['jpg', 'png', 'mp4', 'wav', 'mp3'])
278
+ if uploaded_files:
279
+ for uploaded_file in uploaded_files:
280
+ file_type = uploaded_file.type.split('/')[0]
281
+ file_path = f"uploaded_{uploaded_file.name}"
282
+ with open(file_path, 'wb') as f:
283
+ f.write(uploaded_file.read())
284
+ st.session_state['uploaded_files'].append({
285
+ "Name": uploaded_file.name,
286
+ "Type": file_type,
287
+ "Path": file_path
288
+ })
289
+
290
+ # Galleries and Players
291
+ st.header("๐Ÿ–ผ๏ธ Media Gallery")
292
+ if st.session_state['uploaded_files']:
293
+ images = [f for f in st.session_state['uploaded_files'] if f['Type'] == 'image']
294
+ audios = [f for f in st.session_state['uploaded_files'] if f['Type'] == 'audio']
295
+ videos = [f for f in st.session_state['uploaded_files'] if f['Type'] == 'video']
296
+
297
+ if images:
298
+ st.subheader("Images")
299
+ cols = st.columns(3)
300
+ for i, img in enumerate(images):
301
+ with cols[i % 3]:
302
+ st.image(img['Path'], caption=img['Name'], use_column_width=True)
303
+
304
+ if audios:
305
+ st.subheader("Audio")
306
+ for audio in audios:
307
+ st.audio(audio['Path'], format=f"audio/{audio['Name'].split('.')[-1]}")
308
+ st.write(f"Name: {audio['Name']}")
309
+
310
+ if videos:
311
+ st.subheader("Videos")
312
+ for video in videos:
313
+ st.video(video['Path'])
314
+ st.write(f"Name: {video['Name']}")
315
+ else:
316
+ st.write("No media uploaded yet.")
317
+
318
+ # File History Display
319
+ st.header("๐Ÿ“œ File History")
320
+ if st.session_state['file_history']:
321
+ df = pd.DataFrame(st.session_state['file_history'])
322
+ st.dataframe(df)
323
+ else:
324
+ st.write("No files captured yet.")