Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345672 unmodified lines10111213141516173 unmodified lines21222324252659 unmodified lines86878889909192939495969798991 unmodified line1011021031041051067 unmodified lines11411511611711811912013 unmodified lines13413513613713813914014114214314414514614714814933 unmodified lines18318418518618718818919019122 unmodified lines21421521621721821922022122222322422522622722874 unmodified lines303304305306# app.py# Google Drive → Dropbox mirror (refresh-token based)# ---------------------------------------------------------------# pip install gradio dropbox google-api-python-client google-auth## Secrets to set in Space settings:# - DBX_APP_KEY2 unmodified lines# - APP_PASSWORD (optional gate)# - TRANSLATOR_MAP_JSON (optional, e.g. {"FirstName LastName":"es","Vorname Nachname":"de"})import os, io, re, json, time, randomfrom typing import List, Tuple, Optional, Dict, Callable, Typeimport gradio as grimport dropboxfrom dropbox.exceptions import ApiError, AuthError, HttpError as DbxHttpError3 unmodified linesfrom googleapiclient.http import MediaIoBaseDownloadfrom googleapiclient.errors import HttpError as GHttpError# ===== Secrets / Config =====DBX_APP_KEY = os.environ.get("DBX_APP_KEY", "")DBX_APP_SECRET = os.environ.get("DBX_APP_SECRET", "")59 unmodified linesreturn wrappedreturn deco@retry((AuthError, DbxHttpError, ApiError), tries=3)def ping_dropbox(dbx: dropbox.Dropbox):dbx.users_get_current_account()def list_children(svc, folder_id: str) -> List[dict]:items, page_token = [], Nonewhile True:resp = svc.files().list(q=f"'{folder_id}' in parents and trashed=false",fields="nextPageToken, files(id, name, mimeType)",pageToken=page_token,1 unmodified linesupportsAllDrives=True,includeItemsFromAllDrives=True,).execute()items.extend(resp.get("files", []))page_token = resp.get("nextPageToken")if not page_token:7 unmodified linesp = "/".join(x.strip("/") for x in parts if x and x != "/")return f"/{p}" if p else "/"@retry((ApiError, DbxHttpError), tries=3)def ensure_dropbox_folder(dbx: dropbox.Dropbox, path: str):if path == "/":return13 unmodified linesreturn Falsedef drive_download_to_buffer(svc, file_id: str) -> io.BytesIO:buf = io.BytesIO()request = svc.files().get_media(fileId=file_id)downloader = MediaIoBaseDownload(buf, request)done = Falsewhile not done:_, done = downloader.next_chunk()buf.seek(0)return buf@retry((ApiError, DbxHttpError), tries=3)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"))33 unmodified lineslogs.append(f"✓ {dp}")counters["uploaded"] += 1except (ApiError, DbxHttpError, GHttpError) as e:# Do not surface tokens or secrets—SDK errors won’t include them, but keep it tight.logs.append(f"× {dp} :: {type(e).__name__}: {str(e)[:400]}")counters["failed"] += 1# ===== Core op =====def mirror_course(22 unmodified linesif not root_id:return "", "Invalid Google Drive folder URL."# Clientssvc = gdrive_service()dbx = dbx_from_refresh(dbx_refresh_token)try:ping_dropbox(dbx)except AuthError as e:return "", f"Dropbox auth failed."except (ApiError, DbxHttpError) as e:return "", f"Dropbox connectivity failed."course_root = dpath_join(base_root, course_name)ensure_dropbox_folder(dbx, base_root)74 unmodified lines)if __name__ == "__main__":demo.queue().launch()12345672 unmodified lines1011121314151617183 unmodified lines2223242526272829303132333435363759 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261 unmodified line1281291301311321331341351361371381391401411427 unmodified lines15015115215315415515613 unmodified lines17017117217317417517617717817918018118218318418518618718818919019119219333 unmodified lines22722822923023123223323423523623722 unmodified lines26026126226326426526626726826927027127227327427527627727827928028128228374 unmodified lines358359360361# 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_KEY2 unmodified lines# - APP_PASSWORD (optional gate)# - TRANSLATOR_MAP_JSON (optional, e.g. {"FirstName LastName":"es","Vorname Nachname":"de"})import os, io, re, json, time, random, socketfrom typing import List, Tuple, Optional, Dict, Callable, Typeimport gradio as grimport dropboxfrom dropbox.exceptions import ApiError, AuthError, HttpError as DbxHttpError3 unmodified linesfrom googleapiclient.http import MediaIoBaseDownloadfrom googleapiclient.errors import HttpError as GHttpErrorimport requestsfrom requests import exceptions as req_exctry:# urllib3 v2from urllib3.exceptions import NameResolutionError as Url3NameResolutionErrorexcept Exception: # urllib3 v1 shimclass Url3NameResolutionError(Exception): ...import httplib2# ===== Secrets / Config =====DBX_APP_KEY = os.environ.get("DBX_APP_KEY", "")DBX_APP_SECRET = os.environ.get("DBX_APP_SECRET", "")59 unmodified linesreturn wrappedreturn deco# Network-ish exceptions we want to back off onNET_EXC = (req_exc.ConnectionError,req_exc.Timeout,Url3NameResolutionError,socket.gaierror,httplib2.ServerNotFoundError,)@retry((AuthError, DbxHttpError, ApiError) + NET_EXC, tries=5, base_delay=0.8, max_delay=8.0)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 = Nonereturn code in {500, 502, 503, 504}@retry((GHttpError, httplib2.ServerNotFoundError, socket.gaierror), tries=5, base_delay=0.8, max_delay=8.0)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,1 unmodified linesupportsAllDrives=True,includeItemsFromAllDrives=True,).execute()except GHttpError as e:if _should_retry_ghttp(e):raiseraisedef list_children(svc, folder_id: str) -> List[dict]:items, page_token = [], Nonewhile True:resp = _list_children_page(svc, folder_id, page_token)items.extend(resp.get("files", []))page_token = resp.get("nextPageToken")if not page_token:7 unmodified linesp = "/".join(x.strip("/") for x in parts if x and x != "/")return f"/{p}" if p else "/"@retry((ApiError, DbxHttpError) + NET_EXC, tries=5, base_delay=0.8, max_delay=8.0)def ensure_dropbox_folder(dbx: dropbox.Dropbox, path: str):if path == "/":return13 unmodified linesreturn Falsedef drive_download_to_buffer(svc, file_id: str) -> io.BytesIO:@retry((GHttpError, httplib2.ServerNotFoundError, socket.gaierror), tries=5, base_delay=0.8, max_delay=8.0)def _dl():buf = io.BytesIO()request = svc.files().get_media(fileId=file_id)downloader = MediaIoBaseDownload(buf, request)done = Falsewhile not done:try:_, done = downloader.next_chunk()except GHttpError as e:if _should_retry_ghttp(e):raiseraisebuf.seek(0)return bufreturn _dl()@retry((ApiError, DbxHttpError) + NET_EXC, tries=5, base_delay=0.8, max_delay=8.0)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"))33 unmodified lineslogs.append(f"✓ {dp}")counters["uploaded"] += 1except (ApiError, DbxHttpError, GHttpError) as e:logs.append(f"× {dp} :: {type(e).__name__}: {str(e)[:400]}")counters["failed"] += 1except (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(22 unmodified linesif 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."# Clientssvc = 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)74 unmodified lines)if __name__ == "__main__":demo.queue().launch()
app.py+79-24