Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines7891011122 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061076 unmodified linesAPP_PASSWORD = os.environ.get("APP_PASSWORD", "")FORBIDDEN = {"/": " - ", "\0": ""}def sanitize(name: str) -> str:s = (name or "").strip()2 unmodified linesreturn s[:255]def parse_lines(raw: str) -> List[str]:parts = []if not raw:return []raw = raw.replace("\t", "\n")for chunk in raw.splitlines():parts.append(sanitize(chunk))# de-dup preserving orderseen, out = set(), []for p in parts:if p and p not in seen:seen.add(p)out.append(p)return outdef ensure_base(dbx: dropbox.Dropbox, base: str) -> None:if base == "/":returntry:dbx.files_create_folder_v2(base, autorename=False)except dropbox.exceptions.ApiError:pass # exists or no-opdef dry_preview(names: List[str], parent: str) -> str:base = "/" if not parent.strip() else ("/" + parent.strip().strip("/"))preview = [f"{base}/{n}" if base != "/" else f"/{n}" for n in names]return "No valid folder names found." if not preview else "Folders to create:\n" + "\n".join(preview)def create_folders(pasted: str, parent: str, password: str, dry_run: bool) -> Tuple[str, str]:# Basic gateif APP_PASSWORD and password != APP_PASSWORD:return "", "Wrong password."if not DROPBOX_TOKEN:return "", "Server misconfigured: missing DROPBOX_TOKEN."names = parse_lines(pasted)# Small guardrail to avoid accidental huge jobsif len(names) > 500:return "", f"Too many names ({len(names)}). Limit is 500 per run."parent = "/" if not parent.strip() else ("/" + parent.strip().strip("/"))if dry_run:return dry_preview(names, parent), "Dry run. Nothing created."dbx = dropbox.Dropbox(DROPBOX_TOKEN)ensure_base(dbx, parent)logs = []created, exists, failed = 0, 0, 0for n in names:full = f"{parent}/{n}" if parent != "/" else f"/{n}"try:dbx.files_create_folder_v2(full, autorename=True)logs.append(f"✓ {full}")created += 1except dropbox.exceptions.ApiError as e:try:if e.error.is_path() and e.error.get_path().is_conflict():logs.append(f"• Exists: {full}")exists += 1else:logs.append(f"× Failed: {full} :: {e}")failed += 1except Exception:logs.append(f"× Failed: {full} :: {e}")failed += 1summary = f"Done. Created: {created} · Exists: {exists} · Failed: {failed}"return "\n".join(logs), summarywith gr.Blocks(title="Dropbox Folder Maker") as demo:gr.Markdown("## Dropbox Folder Maker\nPaste names → set parent → create folders.\n""• Only `/` is replaced (with ` - `). • Empty lines ignored. • Duplicates removed.")with gr.Row():pasted = gr.Textbox(lines=14, label="Paste names (one per line; blanks OK)")parent = gr.Textbox(value="/NewFolders", label="Parent Dropbox folder (e.g., /Clients/2025/BatchA)")with gr.Row():password = gr.Textbox(type="password", label="Access password")dry = gr.Checkbox(value=True, label="Dry run (preview only)")run_btn = gr.Button("Run")logs = gr.Textbox(lines=16, label="Log / Preview", interactive=False)status = gr.Markdown("")run_btn.click(fn=create_folders, inputs=[pasted, parent, password, dry], outputs=[logs, status])if __name__ == "__main__":demo.queue().launch()6 unmodified lines789101112132 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431446 unmodified linesAPP_PASSWORD = os.environ.get("APP_PASSWORD", "")FORBIDDEN = {"/": " - ", "\0": ""}LANGS = ["French", "German", "Spanish"] # language folders to createdef sanitize(name: str) -> str:s = (name or "").strip()2 unmodified linesreturn s[:255]def parse_lines(raw: str) -> List[str]:if not raw:return []parts = (raw.replace("\t", "\n")).splitlines()parts = [sanitize(p) for p in parts]seen, out = set(), []for p in parts:if p and p not in seen:seen.add(p); out.append(p)return outdef ensure_folder(dbx: dropbox.Dropbox, path: str) -> None:if path == "/":returntry:dbx.files_create_folder_v2(path, autorename=False)except dropbox.exceptions.ApiError:pass # already exists / conflict is finedef norm_root(root: str) -> str:return "/" if not root.strip() else ("/" + root.strip().strip("/"))def dry_preview(names: List[str], root: str, course: str) -> str:base_root = norm_root(root)course = sanitize(course)if not course:return "Course name is required."course_path = f"{base_root}/{course}" if base_root != "/" else f"/{course}"if not names:return "No valid folder names found."lines = [f"[Course] {course_path}", ""]for lang in LANGS:lang_base = f"{course_path}/{lang}"lines.append(f"[{lang}]")for n in names:lines.append(f"{lang_base}/{n}")lines.append("")return "Folders to create:\n" + "\n".join(lines)def create_folders(pasted: str, root: str, course: str, password: str, dry_run: bool) -> Tuple[str, str]:if APP_PASSWORD and password != APP_PASSWORD:return "", "Wrong password."if not DROPBOX_TOKEN:return "", "Server misconfigured: missing DROPBOX_TOKEN."names = parse_lines(pasted)course = sanitize(course)if not course:return "", "Course name is required."base_root = norm_root(root)course_path = f"{base_root}/{course}" if base_root != "/" else f"/{course}"total_targets = len(names) * len(LANGS)if total_targets > 1500:return "", f"Too many folders requested ({total_targets}). Limit is 1500 per run."if dry_run:return dry_preview(names, base_root, course), "Dry run. Nothing created."dbx = dropbox.Dropbox(DROPBOX_TOKEN)# Ensure /root and /root/course and /root/course/{lang}ensure_folder(dbx, base_root)ensure_folder(dbx, course_path)lang_paths = []for lang in LANGS:lp = f"{course_path}/{lang}"ensure_folder(dbx, lp)lang_paths.append(lp)logs = []created = exists = failed = 0for lp in lang_paths:for n in names:full = f"{lp}/{n}"try:dbx.files_create_folder_v2(full, autorename=True)logs.append(f"✓ {full}")created += 1except dropbox.exceptions.ApiError as e:try:if e.error.is_path() and e.error.get_path().is_conflict():logs.append(f"• Exists: {full}")exists += 1else:logs.append(f"× Failed: {full} :: {e}")failed += 1except Exception:logs.append(f"× Failed: {full} :: {e}")failed += 1summary = f"Done. Created: {created} · Exists: {exists} · Failed: {failed}"return "\n".join(logs), summarywith gr.Blocks(title="Dropbox Course Folder Maker") as demo:gr.Markdown("## Dropbox Course Folder Maker\n""Creates per-name folders inside language subfolders for a course under a base root.\n"f"Structure: `/Course Translations/{{Course}}/{{{', '.join(LANGS)}}}/{{Each Name}}`\n""• Only `/` is replaced (with ` - `). • Empty lines ignored. • Duplicates removed.")with gr.Row():base_root = gr.Textbox(value="/Course Translations", label="Base root (parent path)")course = gr.Textbox(value="", label="Course name (e.g., C3 Acid-Base Essentials)")with gr.Row():pasted = gr.Textbox(lines=12, label="Paste names (one per line; blanks OK)")with gr.Row():password = gr.Textbox(type="password", label="Access password")dry = gr.Checkbox(value=True, label="Dry run (preview only)")run_btn = gr.Button("Run")logs = gr.Textbox(lines=18, label="Log / Preview", interactive=False)status = gr.Markdown("")run_btn.click(fn=create_folders,inputs=[pasted, base_root, course, password, dry],outputs=[logs, status])if __name__ == "__main__":# For Hugging Face Spaces; keep the Space Private; token/password via Secrets.demo.queue().launch()
app.py+85-48