Spaces:
Build error
Build error
| import gradio as gr | |
| import zipfile | |
| import datetime | |
| def add_image(camera, gallery): | |
| if camera is None: | |
| gr.Warning("No Camera Recording!") | |
| return | |
| if gallery is None: | |
| return [camera] | |
| else: | |
| images = gallery | |
| images.append(camera) | |
| return images | |
| def zip_gallery(gallery): | |
| current_time = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S") | |
| new_zip_name = f'{current_time}.zip' | |
| count = 0 | |
| if not gallery: | |
| return gr.DownloadButton("Download", visible=False) | |
| zf = zipfile.ZipFile(new_zip_name, mode="w") | |
| try: | |
| for path, _ in gallery: | |
| zf.write(path, f'{current_time}_{count}.png', | |
| compress_type=zipfile.ZIP_DEFLATED) | |
| count = count + 1 | |
| except FileNotFoundError: | |
| print("Error Occurred!") | |
| gr.Warning("Zip Error!") | |
| finally: | |
| zf.close() | |
| gr.Info(f"Zip Complete. Name: {new_zip_name}") | |
| return gr.DownloadButton("Download/下載", value=new_zip_name, visible=True) | |
| with gr.Blocks(fill_height=True) as demo: | |
| with gr.Accordion("How to Use/使用說明"): | |
| gr.Markdown( | |
| """ | |
| # How to Use | |
| 1. Open Camera on left side, then click "Record" button on the camera screen | |
| 2. Click "Capture" button to capture image to gallery | |
| 3. After capture all image, click "Zip file" button to zip images | |
| 4. Download zip file by clicking "Download" button showed below | |
| # 如何使用 | |
| 1. 點擊左側開啟攝影機,並按下"Record"按鈕讓攝影機能夠進行擷取 | |
| 2. 點擊"Capture"按鈕,影像就會被擷取到下方的欄位中 | |
| 3. 擷取影像完畢後,點擊下方的"Zip file"按鈕將影像打包並壓縮 | |
| 4. 按下隨後出現的"Download"按鈕就能下載打包好的壓縮檔 | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column(): | |
| camera = gr.Image(type="pil", format="png", webcam_constraints={ | |
| "video": {"width": 640, "height": 640}}, sources="webcam", mirror_webcam=False, scale=0) | |
| catch_btn = gr.Button("Capture/拍照", scale=0) | |
| with gr.Column(): | |
| preview_img = gr.Image(visible=False) | |
| gallery = gr.Gallery( | |
| label="Collected images", show_label=False, elem_id="gallery", columns=[10], rows=[4], object_fit="contain", height="auto") | |
| zip_btn = gr.Button("Zip file/打包照片") | |
| download_btn = gr.DownloadButton("Download/下載", visible=False) | |
| catch_btn.click(add_image, [preview_img, gallery], [gallery]) | |
| camera.stream(lambda s: s, camera, preview_img) | |
| zip_btn.click(zip_gallery, gallery, download_btn) | |
| if __name__ == "__main__": | |
| demo.launch() | |