File size: 1,554 Bytes
ab32f57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import gradio as gr
import os
import uuid

from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

# === CONFIG ===
FOLDER_ID = "YOUR_GOOGLE_DRIVE_FOLDER_ID"
SERVICE_ACCOUNT_FILE = "service_account.json"  # Upload this securely in your Space

# === Upload to Google Drive ===
def upload_to_drive(local_file_path, filename_on_drive):
    SCOPES = ['https://www.googleapis.com/auth/drive.file']
    credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    service = build('drive', 'v3', credentials=credentials)

    file_metadata = {
        'name': filename_on_drive,
        'parents': [FOLDER_ID]
    }
    media = MediaFileUpload(local_file_path, mimetype='image/jpeg')

    file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
    return f"Uploaded to Drive with ID: {file.get('id')}"

# === Gradio Camera Interface ===
def handle_photo(image):
    if image is None:
        return "No image captured."

    # Save image locally
    filename = f"captured_{uuid.uuid4().hex}.jpg"
    image.save(filename)

    # Upload to Drive
    result = upload_to_drive(filename, filename)

    # Clean up (optional)
    os.remove(filename)

    return result

iface = gr.Interface(fn=handle_photo, 
                     inputs=gr.Image(source="camera", tool=None), 
                     outputs="text", 
                     title="Capture and Upload Photo to Drive")

iface.launch()