Spaces:
Sleeping
Sleeping
Use password-only gate and rename Hailey AI Agent
Browse filesFiles changed (4)
- .env.example+1-1
- README.md+3-3
- app.py+70-38
- router.py+1-1
12345# Set this as a Hugging Face Space Secret, never commit a real key.OPENROUTER_API_KEY=# Optional password protection when running locally or making the Space public.APP_USERNAME=adminAPP_PASSWORD=12345# Set this as a Hugging Face Space Secret, never commit a real key.OPENROUTER_API_KEY=# Optional password protection when running locally or making the Space public.APP_PASSWORD=REQUIRE_APP_PASSWORD=1
123456 unmodified lines1213141516171856 unmodified lines75767778798081---title: Claude Document Studioemoji: 📚colorFrom: indigocolorTo: purple6 unmodified linesstartup_duration_timeout: 30m---# Claude Document StudioHugging Face Gradio Space,通过 **OpenRouter** 调用 Claude 与 DeepSeek。支持中文多轮聊天、流式输出、联网搜索和文档/图片上传,无需下载模型权重。56 unmodified linesZeroGPU 模式通过环境变量 `USE_ZEROGPU=1` 加载兼容入口;正常聊天仍运行在 CPU,不占用 GPU。该模式需对应账号具备 ZeroGPU 创建资格。公开 Space 前,请先在 Secrets 设置 `APP_PASSWORD`,可选 `APP_USERNAME`(默认 `admin`),并设置环境变量 `REQUIRE_APP_PASSWORD=1`。默认私有部署不额外要求应用密码。## 本地运行123456 unmodified lines1213141516171856 unmodified lines75767778798081---title: Hailey专属AI Agentemoji: 📚colorFrom: indigocolorTo: purple6 unmodified linesstartup_duration_timeout: 30m---# Hailey专属AI AgentHugging Face Gradio Space,通过 **OpenRouter** 调用 Claude 与 DeepSeek。支持中文多轮聊天、流式输出、联网搜索和文档/图片上传,无需下载模型权重。56 unmodified linesZeroGPU 模式通过环境变量 `USE_ZEROGPU=1` 加载兼容入口;正常聊天仍运行在 CPU,不占用 GPU。该模式需对应账号具备 ZeroGPU 创建资格。公开 Space 前,请先在 Secrets 设置 `APP_PASSWORD`,并设置环境变量 `REQUIRE_APP_PASSWORD=1`。应用会先显示仅密码门禁,验证成功后才展示主界面。默认私有部署不额外要求应用密码。## 本地运行
12345624 unmodified lines3132333435369 unmodified lines46474849505152535411 unmodified lines66676869707187 unmodified lines1591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002014 unmodified lines206207208209210211212213214215216217218"""Claude Document Studio — a server-side OpenRouter Space."""import copyimport jsonimport osimport time24 unmodified lines#intro { padding: 18px 4px 8px; }#intro h1 { font-size: 30px; letter-spacing: -0.7px; }#status { font-size: 13px; opacity: .85; min-height: 28px; }#file-help, #file-help .prose, #file-help p {font-family: var(--font);font-size: var(--block-label-text-size);9 unmodified lines]def chat(text: str, files: list[str] | None, session: dict, model: str,search: bool, max_tokens: int, effort: str):"""Chat with Claude using optional documents, images, and web search.Attachments remain in this session for subsequent turns. A successful responsecommits one complete turn; errors and cancelled requests do not commit a turn.11 unmodified linesgr.update(interactive=not busy), gr.update(interactive=not busy))try:if not text and not files:raise FileError("请输入问题或上传文件。")if not os.environ.get("OPENROUTER_API_KEY", "").strip():87 unmodified linesdef create_app() -> gr.Blocks:with gr.Blocks(title="Claude Document Studio", delete_cache=(3600, 3600)) as demo:if os.environ.get("USE_ZEROGPU") == "1":# Registered, hidden, and not exposed through the public API.gr.Button(visible=False).click(_zerogpu_compatibility, api_name=False)gr.Markdown("# Claude Document Studio\nClaude 与 DeepSeek · 文档与图片问答 · 联网搜索", elem_id="intro")session = gr.State({"messages": [], "display": [], "pages": 0}, time_to_live=3600)with gr.Row():with gr.Column(scale=1, min_width=290):model = gr.Dropdown(MODEL_CHOICES, value=DEFAULT_MODEL,label="选择模型 · USD / 1M TOKENS")search = gr.Checkbox(value=True, label="开启联网搜索", info="模型按需检索;搜索另行计费。")files = gr.File(label="上传 PDF / WORD / POWERPOINT / EXCEL / IMAGES",file_count="multiple", file_types=ALLOWED, type="filepath")gr.Markdown("PDF · WORD (DOC/DOCX) · POWERPOINT (PPT/PPTX) · ""EXCEL (XLS/XLSX/CSV) · IMAGES\n\n""每次 ≤ 8 个文件,单文件 ≤ 15 MB,总计 ≤ 20 MB;会话 PDF ≤ 100 页。""EXCEL 读取单元格和公式,不读取嵌入图表。",elem_id="file-help")with gr.Accordion("生成设置", open=False):effort = gr.Dropdown([("低", "low"), ("中", "medium"), ("高", "high"),("更高", "xhigh"), ("最高", "max")], value="medium", label="推理强度")max_tokens = gr.Slider(1024, 32768, value=8192, step=1024, label="输出上限(含推理 tokens)")with gr.Column(scale=3, min_width=440):chatbot = gr.Chatbot(height=540, label="对话", layout="bubble")prompt = gr.Textbox(label="输入问题", placeholder="输入问题,或上传文件后让我分析…", lines=3)with gr.Row():send = gr.Button("发送", variant="primary")stop = gr.Button("停止")clear = gr.Button("新建对话")status = gr.Markdown("就绪 · 联网搜索默认开启", elem_id="status")gr.Examples([["请联网查询今天的重要科技新闻,附上日期与来源。"],["请总结���件的核心结论、证据和待确认问题。"],["请分析表格中的趋势、异常值与可能原因。"]], inputs=[prompt], cache_examples=False)gr.Markdown("附件内容会发送至 OpenRouter 及所选模型供应商。对话仅保留在当前服务会话,""刷新页面或会话过期后可能丢失;临时上传文件定时清理。")outputs = [chatbot, session, prompt, files, status, send, clear]event = send.click(chat, inputs=[prompt, files, session, model, search, max_tokens, effort],outputs=outputs, api_name="chat", concurrency_limit=2, trigger_mode="once")stop.click(stop_chat, inputs=[session], outputs=[chatbot, prompt, files, status, send, clear],cancels=[event], queue=False, api_name=False)4 unmodified linesdemo = create_app()if __name__ == "__main__":password = os.environ.get("APP_PASSWORD")auth = (os.environ.get("APP_USERNAME", "admin"), password) if password else Noneif os.environ.get("REQUIRE_APP_PASSWORD") == "1" and not auth:raise RuntimeError("Set APP_PASSWORD in Space Secrets before starting this public Space.")demo.queue(max_size=16).launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", "7860")),theme=gr.themes.Soft(primary_hue="indigo"), css=CSS,auth=auth, auth_message="请输入访问密码", max_file_size="15mb", show_error=False,run_history=False, state_session_capacity=100,allowed_paths=[], blocked_paths=[str(Path(__file__).parent / ".env")],)123456724 unmodified lines323334353637389 unmodified lines48495051525354555657585960616263646566676811 unmodified lines808182838485868787 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332344 unmodified lines239240241242243244245246247248249250"""Hailey's private AI agent backed by OpenRouter."""import copyimport hmacimport jsonimport osimport time24 unmodified lines#intro { padding: 18px 4px 8px; }#intro h1 { font-size: 30px; letter-spacing: -0.7px; }#status { font-size: 13px; opacity: .85; min-height: 28px; }#login-panel { max-width: 420px; margin: 12vh auto; padding: 24px; }#file-help, #file-help .prose, #file-help p {font-family: var(--font);font-size: var(--block-label-text-size);9 unmodified lines]def unlock(password: str) -> tuple:"""Reveal the app only when the password matches the server-side Secret."""expected = os.environ.get("APP_PASSWORD", "")if expected and hmac.compare_digest(password or "", expected):return (gr.update(visible=False), gr.update(visible=True), True,gr.update(value=""), "")# Slow repeated guesses without delaying successful logins.time.sleep(0.75)return (gr.update(visible=True), gr.update(visible=False), False,gr.update(value=""), "密码错误,请重试。")def chat(text: str, files: list[str] | None, session: dict, model: str,search: bool, max_tokens: int, effort: str, authorized: bool):"""Chat with the selected model using documents, images, and web search.Attachments remain in this session for subsequent turns. A successful responsecommits one complete turn; errors and cancelled requests do not commit a turn.11 unmodified linesgr.update(interactive=not busy), gr.update(interactive=not busy))try:if not authorized:raise RouterError("请先输入访问密码。")if not text and not files:raise FileError("请输入问题或上传文件。")if not os.environ.get("OPENROUTER_API_KEY", "").strip():87 unmodified linesdef create_app() -> gr.Blocks:password_required = bool(os.environ.get("APP_PASSWORD")) or os.environ.get("REQUIRE_APP_PASSWORD") == "1"with gr.Blocks(title="Hailey专属AI Agent", delete_cache=(3600, 3600)) as demo:if os.environ.get("USE_ZEROGPU") == "1":# Registered, hidden, and not exposed through the public API.gr.Button(visible=False).click(_zerogpu_compatibility, api_name=False)authorized = gr.State(not password_required, time_to_live=3600)session = gr.State({"messages": [], "display": [], "pages": 0}, time_to_live=3600)with gr.Column(visible=password_required, elem_id="login-panel") as login_panel:gr.Markdown("## Hailey专属AI Agent\n请输入访问密码")password_input = gr.Textbox(label="访问密码", type="password", autofocus=True)login_button = gr.Button("进入", variant="primary")login_status = gr.Markdown("")with gr.Column(visible=not password_required) as app_panel:gr.Markdown("# Hailey专属AI Agent\nClaude 与 DeepSeek · 文档与图片问答 · 联网搜索", elem_id="intro")with gr.Row():with gr.Column(scale=1, min_width=290):model = gr.Dropdown(MODEL_CHOICES, value=DEFAULT_MODEL,label="选择模型 · USD / 1M TOKENS")search = gr.Checkbox(value=True, label="开启联网搜索", info="模型按需检索;搜索另行计费。")files = gr.File(label="上传 PDF / WORD / POWERPOINT / EXCEL / IMAGES",file_count="multiple", file_types=ALLOWED, type="filepath")gr.Markdown("PDF · WORD (DOC/DOCX) · POWERPOINT (PPT/PPTX) · ""EXCEL (XLS/XLSX/CSV) · IMAGES\n\n""每次 ≤ 8 个文件,单文件 ≤ 15 MB,总计 ≤ 20 MB;会话 PDF ≤ 100 页。""EXCEL 读取单元格和公式,不读取嵌入图表。",elem_id="file-help")with gr.Accordion("生成设置", open=False):effort = gr.Dropdown([("低", "low"), ("中", "medium"), ("高", "high"),("更高", "xhigh"), ("最高", "max")], value="medium", label="推理强度")max_tokens = gr.Slider(1024, 32768, value=8192, step=1024,label="输出上限(含推理 tokens)")with gr.Column(scale=3, min_width=440):chatbot = gr.Chatbot(height=540, label="对话", layout="bubble")prompt = gr.Textbox(label="输入问题", placeholder="输入问题,或上传文件后让我分析…", lines=3)with gr.Row():send = gr.Button("发送", variant="primary")stop = gr.Button("停止")clear = gr.Button("新建对话")status = gr.Markdown("就绪 · 联网搜索默认开启", elem_id="status")gr.Examples([["请联网查询今天的重要科技新闻,附上日期与来源。"],["请总结附件的核心结论、证据和待确认问题。"],["请分析表格中的趋势、异常值与可能原因。"]],inputs=[prompt], cache_examples=False)gr.Markdown("附件内容会发送至 OpenRouter 及所选模型供应商。对话仅保留在当前服务会话,""刷新页面或会话过期后可能丢失;临时上传文件定时清理。")gate_outputs = [login_panel, app_panel, authorized, password_input, login_status]login_button.click(unlock, inputs=[password_input], outputs=gate_outputs,queue=False, api_name=False)password_input.submit(unlock, inputs=[password_input], outputs=gate_outputs,queue=False, api_name=False)outputs = [chatbot, session, prompt, files, status, send, clear]event = send.click(chat, inputs=[prompt, files, session, model, search, max_tokens, effort, authorized],outputs=outputs, api_name="chat", concurrency_limit=2, trigger_mode="once")stop.click(stop_chat, inputs=[session], outputs=[chatbot, prompt, files, status, send, clear],cancels=[event], queue=False, api_name=False)4 unmodified linesdemo = create_app()if __name__ == "__main__":password = os.environ.get("APP_PASSWORD")if os.environ.get("REQUIRE_APP_PASSWORD") == "1" and not password:raise RuntimeError("Set APP_PASSWORD in Space Secrets before starting this public Space.")demo.queue(max_size=16).launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", "7860")),theme=gr.themes.Soft(primary_hue="indigo"), css=CSS,max_file_size="15mb", show_error=False,run_history=False, state_session_capacity=100,allowed_paths=[], blocked_paths=[str(Path(__file__).parent / ".env")],)
47 unmodified lines4849505152535447 unmodified lineskey = os.environ.get("OPENROUTER_API_KEY", "").strip()if not key:raise RouterError("请在 Space Settings → Secrets 中设置 OPENROUTER_API_KEY。")headers = {"Authorization": f"Bearer {key}", "X-Title": "Claude Document Studio"}try:with httpx.Client(timeout=httpx.Timeout(300, connect=20)) as client:with client.stream("POST", f"{API_BASE}/chat/completions", headers=headers, json=payload) as response:47 unmodified lines4849505152535447 unmodified lineskey = os.environ.get("OPENROUTER_API_KEY", "").strip()if not key:raise RouterError("请在 Space Settings → Secrets 中设置 OPENROUTER_API_KEY。")headers = {"Authorization": f"Bearer {key}", "X-Title": "Hailey AI Agent"}try:with httpx.Client(timeout=httpx.Timeout(300, connect=20)) as client:with client.stream("POST", f"{API_BASE}/chat/completions", headers=headers, json=payload) as response:
.env.example+1-1
README.md+3-3
app.py+70-38
router.py+1-1