Spaces:
Sleeping
Sleeping
Download app.py from summersomersault/DBFolderCreator: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/spaces/summersomersault/DBFolderCreator/resolve/main/app.py
- Command line
-
hf download hf://spaces/summersomersault/DBFolderCreator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/summersomersault/DBFolderCreator/resolve/main/app.py
13.2 kB
| # app.py | |
| # Google Drive → Dropbox mirror (refresh-token based) | |
| # --------------------------------------------------------------- | |
| # pip install gradio dropbox google-api-python-client google-auth requests httplib2 | |
| # | |
| # Secrets to set in Space settings: | |
| # - DBX_APP_KEY | |
| # - DBX_APP_SECRET | |
| # - GDRIVE_SA_JSON (full JSON of a service account with Drive read access) | |
| # - APP_PASSWORD (optional gate) | |
| # - TRANSLATOR_MAP_JSON (optional, e.g. {"FirstName LastName":"es","Vorname Nachname":"de"}) | |
| import os, io, re, json, time, random, socket | |
| from typing import List, Tuple, Optional, Dict, Callable, Type | |
| import gradio as gr | |
| import dropbox | |
| from dropbox.exceptions import ApiError, AuthError, HttpError as DbxHttpError | |
| from google.oauth2 import service_account | |
| from googleapiclient.discovery import build | |
| from googleapiclient.http import MediaIoBaseDownload | |
| from googleapiclient.errors import HttpError as GHttpError | |
| import requests | |
| from requests import exceptions as req_exc | |
| try: | |
| # urllib3 v2 | |
| from urllib3.exceptions import NameResolutionError as Url3NameResolutionError | |
| except Exception: # urllib3 v1 shim | |
| class Url3NameResolutionError(Exception): ... | |
| import httplib2 | |
| # ===== Secrets / Config ===== | |
| DBX_APP_KEY = os.environ.get("DBX_APP_KEY", "") | |
| DBX_APP_SECRET = os.environ.get("DBX_APP_SECRET", "") | |
| SA_JSON = os.environ.get("GDRIVE_SA_JSON", "") | |
| APP_PASSWORD = os.environ.get("APP_PASSWORD", "") | |
| HARDCODED_MAP = {k.lower(): v for k, v in json.loads(os.environ.get("TRANSLATOR_MAP_JSON", "{}")).items()} | |
| FORBIDDEN = {"/": " - ", "\0": ""} | |
| GDRIVE_SCOPE = ["https://www.googleapis.com/auth/drive.readonly"] | |
| # ===== Utilities ===== | |
| def sanitize(name: str) -> str: | |
| s = (name or "").strip() | |
| for bad, repl in FORBIDDEN.items(): | |
| s = s.replace(bad, repl) | |
| return s[:255] or "untitled" | |
| def extract_folder_id_from_url(url: str) -> Optional[str]: | |
| m = re.search(r"/folders/([a-zA-Z0-9_-]+)", (url or "").strip()) | |
| return m.group(1) if m else None | |
| def guard(pw: str) -> bool: | |
| return (APP_PASSWORD == "") or (pw == APP_PASSWORD) | |
| def gdrive_service(): | |
| if not SA_JSON: | |
| raise RuntimeError("Missing GDRIVE_SA_JSON secret.") | |
| info = json.loads(SA_JSON) | |
| creds = service_account.Credentials.from_service_account_info(info, scopes=GDRIVE_SCOPE) | |
| return build("drive", "v3", credentials=creds, cache_discovery=False) | |
| def dbx_from_refresh(rt: str) -> dropbox.Dropbox: | |
| if not (DBX_APP_KEY and DBX_APP_SECRET): | |
| raise RuntimeError("Missing DBX_APP_KEY/DBX_APP_SECRET on server.") | |
| if not rt.strip(): | |
| raise RuntimeError("Dropbox refresh token missing.") | |
| # Official SDK will auto-exchange/refresh using key+secret+RT. | |
| return dropbox.Dropbox( | |
| app_key=DBX_APP_KEY, | |
| app_secret=DBX_APP_SECRET, | |
| oauth2_refresh_token=rt.strip(), | |
| timeout=300, | |
| ) | |
| def retry( | |
| exceptions: Tuple[Type[BaseException], ...], | |
| tries: int = 3, | |
| base_delay: float = 0.5, | |
| max_delay: float = 5.0, | |
| ): | |
| def deco(fn: Callable): | |
| def wrapped(*args, **kwargs): | |
| attempt = 0 | |
| while True: | |
| try: | |
| return fn(*args, **kwargs) | |
| except exceptions as e: | |
| attempt += 1 | |
| if attempt >= tries: | |
| raise | |
| sleep = min(max_delay, base_delay * (2 ** (attempt - 1))) * (1 + 0.1 * random.random()) | |
| time.sleep(sleep) | |
| return wrapped | |
| return deco | |
| # Network-ish exceptions we want to back off on | |
| NET_EXC = ( | |
| req_exc.ConnectionError, | |
| req_exc.Timeout, | |
| Url3NameResolutionError, | |
| socket.gaierror, | |
| httplib2.ServerNotFoundError, | |
| ) | |
| def ping_dropbox(dbx: dropbox.Dropbox): | |
| dbx.users_get_current_account() | |
| def _should_retry_ghttp(e: GHttpError) -> bool: | |
| try: | |
| code = int(getattr(e, "resp", None).status) | |
| except Exception: | |
| code = None | |
| return code in {500, 502, 503, 504} | |
| def _list_children_page(svc, folder_id: str, page_token: Optional[str]) -> dict: | |
| try: | |
| return svc.files().list( | |
| q=f"'{folder_id}' in parents and trashed=false", | |
| fields="nextPageToken, files(id, name, mimeType)", | |
| pageToken=page_token, | |
| pageSize=1000, | |
| supportsAllDrives=True, | |
| includeItemsFromAllDrives=True, | |
| ).execute() | |
| except GHttpError as e: | |
| if _should_retry_ghttp(e): | |
| raise | |
| raise | |
| def list_children(svc, folder_id: str) -> List[dict]: | |
| items, page_token = [], None | |
| while True: | |
| resp = _list_children_page(svc, folder_id, page_token) | |
| items.extend(resp.get("files", [])) | |
| page_token = resp.get("nextPageToken") | |
| if not page_token: | |
| break | |
| return items | |
| def is_folder(item: dict) -> bool: | |
| return item.get("mimeType") == "application/vnd.google-apps.folder" | |
| def dpath_join(*parts: str) -> str: | |
| p = "/".join(x.strip("/") for x in parts if x and x != "/") | |
| return f"/{p}" if p else "/" | |
| def ensure_dropbox_folder(dbx: dropbox.Dropbox, path: str): | |
| if path == "/": | |
| return | |
| try: | |
| dbx.files_create_folder_v2(path, autorename=False) | |
| except ApiError: | |
| # Exists or conflict → fine | |
| pass | |
| def should_skip(dbx: dropbox.Dropbox, dest_path: str, overwrite: bool) -> bool: | |
| if overwrite: | |
| return False | |
| try: | |
| dbx.files_get_metadata(dest_path) | |
| return True | |
| except ApiError: | |
| return False | |
| def drive_download_to_buffer(svc, file_id: str) -> io.BytesIO: | |
| def _dl(): | |
| buf = io.BytesIO() | |
| request = svc.files().get_media(fileId=file_id) | |
| downloader = MediaIoBaseDownload(buf, request) | |
| done = False | |
| while not done: | |
| try: | |
| _, done = downloader.next_chunk() | |
| except GHttpError as e: | |
| if _should_retry_ghttp(e): | |
| raise | |
| raise | |
| buf.seek(0) | |
| return buf | |
| return _dl() | |
| def upload_file(dbx: dropbox.Dropbox, dest_path: str, stream: io.BytesIO): | |
| stream.seek(0) | |
| dbx.files_upload(stream.read(), dest_path, mode=dropbox.files.WriteMode("overwrite")) | |
| # ===== Recursive mirror ===== | |
| def mirror_tree( | |
| svc, | |
| dbx, | |
| drive_folder_id: str, | |
| dest_root: str, | |
| overwrite: bool, | |
| dry_run: bool, | |
| logs: List[str], | |
| counters: Dict[str, int], | |
| actor_label: str, | |
| ): | |
| ensure_dropbox_folder(dbx, dest_root) | |
| for item in list_children(svc, drive_folder_id): | |
| name = sanitize(item["name"]) | |
| if is_folder(item): | |
| sub_dest = dpath_join(dest_root, name) | |
| ensure_dropbox_folder(dbx, sub_dest) | |
| mirror_tree(svc, dbx, item["id"], sub_dest, overwrite, dry_run, logs, counters, actor_label) | |
| else: | |
| dp = dpath_join(dest_root, name) | |
| if dry_run: | |
| logs.append(f"[DRY] {actor_label} → {dp}") | |
| counters["planned"] += 1 | |
| continue | |
| if should_skip(dbx, dp, overwrite): | |
| logs.append(f"• Exists, skipped: {dp}") | |
| counters["skipped"] += 1 | |
| continue | |
| try: | |
| buf = drive_download_to_buffer(svc, item["id"]) | |
| upload_file(dbx, dp, buf) | |
| logs.append(f"✓ {dp}") | |
| counters["uploaded"] += 1 | |
| except (ApiError, DbxHttpError, GHttpError) as e: | |
| logs.append(f"× {dp} :: {type(e).__name__}: {str(e)[:400]}") | |
| counters["failed"] += 1 | |
| except (req_exc.ConnectionError, req_exc.Timeout, Url3NameResolutionError, socket.gaierror, httplib2.ServerNotFoundError) as e: | |
| logs.append(f"× {dp} :: NetworkError: {type(e).__name__}: {str(e)[:200]}") | |
| counters["failed"] += 1 | |
| # ===== Core op ===== | |
| def mirror_course( | |
| intake_url: str, | |
| course_name: str, | |
| base_root: str, | |
| only_translators: str, | |
| overwrite: bool, | |
| dry_run: bool, | |
| password: str, | |
| dbx_refresh_token: str, | |
| ) -> Tuple[str, str]: | |
| if not guard(password): | |
| return "", "Wrong password." | |
| if not (DBX_APP_KEY and DBX_APP_SECRET): | |
| return "", "Missing Dropbox app key/secret on server." | |
| if not dbx_refresh_token.strip(): | |
| return "", "Dropbox refresh token missing." | |
| course_name = sanitize(course_name) | |
| if not course_name: | |
| return "", "Course name required." | |
| base_root = "/" if not base_root.strip() else ("/" + base_root.strip().strip("/")) | |
| root_id = extract_folder_id_from_url(intake_url) | |
| if not root_id: | |
| return "", "Invalid Google Drive folder URL." | |
| # DNS warm-up (clear signal if host networking is borked) | |
| for host in ("www.googleapis.com", "api.dropboxapi.com"): | |
| try: | |
| socket.gethostbyname(host) | |
| except Exception: | |
| return "", f"DNS/network failure resolving {host} from host environment." | |
| # Clients | |
| svc = gdrive_service() | |
| dbx = dbx_from_refresh(dbx_refresh_token) | |
| try: | |
| ping_dropbox(dbx) | |
| except AuthError: | |
| return "", "Dropbox auth failed." | |
| except (ApiError, DbxHttpError): | |
| return "", "Dropbox connectivity failed." | |
| except (req_exc.ConnectionError, req_exc.Timeout, Url3NameResolutionError, socket.gaierror, httplib2.ServerNotFoundError): | |
| return "", "Dropbox DNS/network failure from host environment." | |
| course_root = dpath_join(base_root, course_name) | |
| ensure_dropbox_folder(dbx, base_root) | |
| ensure_dropbox_folder(dbx, course_root) | |
| allow = {x.strip().lower() for x in (only_translators or "").split(",") if x.strip()} | |
| logs: List[str] = [] | |
| counters = {"uploaded": 0, "skipped": 0, "failed": 0, "planned": 0} | |
| translators = list_children(svc, root_id) | |
| found_any = False | |
| for t in translators: | |
| if not is_folder(t): | |
| continue | |
| t_name = (t["name"] or "").strip() | |
| t_key = t_name.lower() | |
| if allow and t_key not in allow: | |
| continue | |
| # find matching course folder(s) beneath this translator | |
| for c in list_children(svc, t["id"]): | |
| if not is_folder(c): | |
| continue | |
| if (c["name"] or "").strip().lower() != course_name.lower(): | |
| continue | |
| found_any = True | |
| lang = HARDCODED_MAP.get(t_key) | |
| dest_root = dpath_join(course_root, lang) if lang else course_root | |
| ensure_dropbox_folder(dbx, dest_root) | |
| # mirror everything below the course folder (Intro/Lesson/Quiz/Title/Files…) | |
| mirror_tree(svc, dbx, c["id"], dest_root, overwrite, dry_run, logs, counters, actor_label=t_name) | |
| if not found_any: | |
| return "", f"No matching course '{course_name}' found under any translator." | |
| if dry_run: | |
| summary = f"Dry run. Would upload: {counters['planned']}" | |
| else: | |
| summary = f"Done. Uploaded: {counters['uploaded']} · Skipped: {counters['skipped']} · Failed: {counters['failed']}" | |
| return "\n".join(logs)[:200000], summary # cap logs | |
| # ===== UI ===== | |
| with gr.Blocks( | |
| title="Drive → Dropbox Course Ingest", | |
| analytics_enabled=False, | |
| ) as demo: | |
| gr.Markdown( | |
| "### Drive → Dropbox Course Ingest\n" | |
| "Mirrors files from a shared Google Drive intake into Dropbox.\n" | |
| "Drive: `{IntakeRoot}/{Translator}/{Course}/...` → Dropbox: `/{Base}/{Course}/[Language]/...`" | |
| ) | |
| with gr.Row(): | |
| pw = gr.Textbox(type="password", label="Access password") | |
| dbx_refresh = gr.Textbox(type="password", label="Dropbox refresh token (paste per run)") | |
| with gr.Row(): | |
| intake = gr.Textbox(label="Drive intake folder URL", placeholder="https://drive.google.com/drive/folders/<ID>") | |
| base_root = gr.Textbox(value="/Course Translations", label="Dropbox base root") | |
| with gr.Row(): | |
| course = gr.Textbox(label="Course name (exact match)") | |
| only_translators = gr.Textbox(label="Only these translators (comma-separated, optional)") | |
| with gr.Row(): | |
| overwrite = gr.Checkbox(value=False, label="Overwrite existing files in Dropbox") | |
| dry = gr.Checkbox(value=True, label="Dry run (no uploads)") | |
| run_btn = gr.Button("Run", variant="primary") | |
| logs = gr.Textbox(lines=22, label="Log", interactive=False, show_copy_button=True) | |
| status = gr.Markdown() | |
| run_btn.click( | |
| fn=mirror_course, | |
| inputs=[intake, course, base_root, only_translators, overwrite, dry, pw, dbx_refresh], | |
| outputs=[logs, status], | |
| api_name="mirror", | |
| ) | |
| if __name__ == "__main__": | |
| demo.queue().launch() | |