Spaces:
Sleeping
Sleeping
Download app.py from ChuLiJ/question-optimizer-agent: direct link, hf CLI and curl.
- Browser
- Download file 22.1 kB
-
https://huggingface.co/spaces/ChuLiJ/question-optimizer-agent/resolve/main/app.py
- Command line
-
hf download hf://spaces/ChuLiJ/question-optimizer-agent/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ChuLiJ/question-optimizer-agent/resolve/main/app.py
22.1 kB
| """ | |
| 通用问题优化与求解智能体 | |
| 功能:原始问题 -> Prompt 优化 -> 联网搜索 -> 综合求解 -> 自动生成 PDF 报告 | |
| 运行: | |
| 1. pip install -r requirements.txt | |
| 2. 复制 .env.example 为 .env,并填入 OPENAI_API_KEY / OPENAI_BASE_URL / MODEL_NAME | |
| 3. python app.py | |
| """ | |
| from __future__ import annotations | |
| import datetime as dt | |
| import json | |
| import os | |
| import re | |
| import traceback | |
| import uuid | |
| from dataclasses import dataclass | |
| from html import escape | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Tuple | |
| import gradio as gr | |
| from dotenv import load_dotenv | |
| from openai import OpenAI | |
| # DuckDuckGo 搜索库:兼容 ddgs 与 duckduckgo_search 两种包名 | |
| try: | |
| from ddgs import DDGS # type: ignore | |
| except Exception: # pragma: no cover | |
| try: | |
| from duckduckgo_search import DDGS # type: ignore | |
| except Exception: # pragma: no cover | |
| DDGS = None # type: ignore | |
| from reportlab.lib import colors | |
| from reportlab.lib.enums import TA_CENTER, TA_LEFT | |
| from reportlab.lib.pagesizes import A4 | |
| from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet | |
| from reportlab.lib.units import cm | |
| from reportlab.platypus import ( | |
| ListFlowable, | |
| ListItem, | |
| PageBreak, | |
| Paragraph, | |
| Preformatted, | |
| SimpleDocTemplate, | |
| Spacer, | |
| Table, | |
| TableStyle, | |
| ) | |
| from reportlab.pdfbase import pdfmetrics | |
| from reportlab.pdfbase.cidfonts import UnicodeCIDFont | |
| from reportlab.pdfbase.ttfonts import TTFont | |
| load_dotenv() | |
| APP_DIR = Path(__file__).resolve().parent | |
| OUTPUT_DIR = APP_DIR / "outputs" | |
| OUTPUT_DIR.mkdir(exist_ok=True) | |
| DEFAULT_MODEL = os.getenv("MODEL_NAME", "deepseek-chat") | |
| DEFAULT_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.deepseek.com") | |
| DEFAULT_MAX_RESULTS = int(os.getenv("MAX_SEARCH_RESULTS", "5")) | |
| class SearchItem: | |
| title: str | |
| url: str | |
| snippet: str | |
| def get_client() -> OpenAI: | |
| """创建 OpenAI-compatible 客户端。""" | |
| api_key = os.getenv("OPENAI_API_KEY", "").strip() | |
| base_url = os.getenv("OPENAI_BASE_URL", DEFAULT_BASE_URL).strip() | |
| if not api_key: | |
| raise RuntimeError( | |
| "未检测到 OPENAI_API_KEY。请先复制 .env.example 为 .env,并填写你的公开大模型 API Key。" | |
| ) | |
| return OpenAI(api_key=api_key, base_url=base_url) | |
| def call_llm(messages: List[Dict[str, str]], temperature: float = 0.2) -> str: | |
| """调用聊天模型。""" | |
| client = get_client() | |
| model_name = os.getenv("MODEL_NAME", DEFAULT_MODEL).strip() | |
| response = client.chat.completions.create( | |
| model=model_name, | |
| messages=messages, | |
| # temperature=temperature, | |
| ) | |
| return response.choices[0].message.content or "" | |
| def extract_json(text: str) -> Dict[str, Any]: | |
| """从 LLM 输出中尽量提取 JSON。""" | |
| text = text.strip() | |
| # 直接解析 | |
| try: | |
| return json.loads(text) | |
| except Exception: | |
| pass | |
| # 解析 ```json ... ``` | |
| fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.S) | |
| if fenced: | |
| try: | |
| return json.loads(fenced.group(1)) | |
| except Exception: | |
| pass | |
| # 解析第一个大括号块 | |
| start = text.find("{") | |
| end = text.rfind("}") | |
| if start != -1 and end != -1 and end > start: | |
| candidate = text[start : end + 1] | |
| try: | |
| return json.loads(candidate) | |
| except Exception: | |
| pass | |
| # 兜底 | |
| return { | |
| "original_question": "", | |
| "core_goal": "未能解析结构化结果", | |
| "ambiguities": [], | |
| "assumptions": [], | |
| "optimized_prompt": text, | |
| "search_query": text[:120], | |
| "solution_plan": [], | |
| "pdf_outline": [], | |
| } | |
| def optimize_question(user_question: str) -> Dict[str, Any]: | |
| """第一阶段:问题理解与 Prompt 优化。""" | |
| system_prompt = """ | |
| 你是一个“通用问题优化智能体”。你的任务是把用户模糊、宽泛、不完整的问题,改写成目标明确、条件清晰、可执行、适合大模型求解的高质量 Prompt。 | |
| 你必须严格输出 JSON,不要输出 Markdown,不要输出解释性废话。 | |
| JSON 字段如下: | |
| { | |
| "original_question": "用户原始问题", | |
| "core_goal": "用户真正想解决的核心目标", | |
| "ambiguities": ["原始问题中的模糊点1", "模糊点2"], | |
| "assumptions": ["在不改变用户原意前提下采用的合理假设1", "合理假设2"], | |
| "optimized_prompt": "优化后的高质量 Prompt。要求包含背景、目标、约束、输出格式、评价标准。", | |
| "search_query": "适合联网搜索的查询语句,尽量简洁明确", | |
| "solution_plan": ["步骤1", "步骤2", "步骤3"], | |
| "pdf_outline": ["PDF报告章节1", "PDF报告章节2", "PDF报告章节3"] | |
| } | |
| 要求: | |
| 1. 不要改变用户原意。 | |
| 2. 如果信息缺失,可以给出合理假设,但必须写入 assumptions。 | |
| 3. search_query 要能直接用于搜索引擎。 | |
| 4. optimized_prompt 要足够具体,使另一个模型可以据此完成任务。 | |
| """.strip() | |
| user_prompt = f"用户原始问题:\n{user_question}" | |
| raw = call_llm( | |
| [ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": user_prompt}, | |
| ], | |
| temperature=0.1, | |
| ) | |
| data = extract_json(raw) | |
| data["original_question"] = data.get("original_question") or user_question | |
| data["_raw_output"] = raw | |
| return data | |
| def search_web(query: str, max_results: int = DEFAULT_MAX_RESULTS) -> Tuple[List[SearchItem], str]: | |
| """第二阶段:轻量工具调用,使用 DuckDuckGo 搜索。""" | |
| if DDGS is None: | |
| return [], "未安装 ddgs 或 duckduckgo_search,已跳过联网搜索。" | |
| query = (query or "").strip() | |
| if max_results <= 0: | |
| return [], "已按设置跳过联网搜索。" | |
| if not query: | |
| return [], "搜索关键词为空,已跳过联网搜索。" | |
| try: | |
| items: List[SearchItem] = [] | |
| with DDGS() as ddgs: | |
| results = ddgs.text(query, max_results=max_results) | |
| for r in results: | |
| items.append( | |
| SearchItem( | |
| title=str(r.get("title", "无标题")), | |
| url=str(r.get("href") or r.get("url") or ""), | |
| snippet=str(r.get("body") or r.get("snippet") or ""), | |
| ) | |
| ) | |
| return items, "搜索成功" | |
| except Exception as exc: | |
| return [], f"联网搜索失败,已继续使用模型自身能力求解。错误信息:{exc}" | |
| def format_search_results(items: List[SearchItem], status: str) -> str: | |
| if not items: | |
| return f"搜索状态:{status}\n\n未获得可用搜索结果。" | |
| lines = [f"搜索状态:{status}", ""] | |
| for i, item in enumerate(items, 1): | |
| lines.append(f"[{i}] {item.title}") | |
| lines.append(f"链接:{item.url}") | |
| lines.append(f"摘要:{item.snippet}") | |
| lines.append("") | |
| return "\n".join(lines) | |
| def generate_report(user_question: str, optimized: Dict[str, Any], search_text: str) -> str: | |
| """第三阶段:综合求解,输出适合 PDF 的 Markdown 报告。""" | |
| optimized_json = json.dumps(optimized, ensure_ascii=False, indent=2) | |
| system_prompt = """ | |
| 你是一个“通用问题优化与求解智能体”。你不是简单回答问题,而是需要展示完整求解过程:原始问题理解、模糊点分析、Prompt 优化、联网信息整合、最终解答、结果检查,并输出可转换为 PDF 的详细 Markdown 报告。 | |
| 输出要求: | |
| 1. 必须使用 Markdown。 | |
| 2. 必须适合作为课程作业提交的 PDF 报告。 | |
| 3. 不要虚构联网搜索结果。如果搜索结果不足,明确说明。 | |
| 4. 对来源信息只基于提供给你的搜索结果进行概括。 | |
| 5. 最终解答要具体、可执行。 | |
| 6. 报告中必须体现“问题优化智能体”的工作流程。 | |
| 报告结构必须如下: | |
| # 通用问题优化智能体求解报告 | |
| ## 1. 原始问题 | |
| ## 2. 问题理解与模糊点分析 | |
| ## 3. 优化后的高质量 Prompt | |
| ## 4. 求解计划 | |
| ## 5. 联网搜索参考信息 | |
| ## 6. 综合分析与最终解答 | |
| ## 7. 结果检查与局限性 | |
| ## 8. 行动清单 | |
| ## 9. 本次智能体运行过程总结 | |
| """.strip() | |
| user_prompt = f""" | |
| 下面是本次智能体运行所需的信息。 | |
| 【用户原始问题】 | |
| {user_question} | |
| 【问题优化节点输出】 | |
| {optimized_json} | |
| 【联网搜索结果】 | |
| {search_text} | |
| 请基于以上内容生成完整 Markdown 报告。 | |
| """.strip() | |
| return call_llm( | |
| [ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": user_prompt}, | |
| ], | |
| temperature=0.25, | |
| ) | |
| def register_chinese_font() -> str: | |
| """ | |
| 注册中文字体,优先使用系统中文字体,避免 PDF 中文乱码。 | |
| """ | |
| font_name = "ChineseFont" | |
| candidate_fonts = [ | |
| # Windows 本地调试 | |
| r"C:\Windows\Fonts\simhei.ttf", | |
| r"C:\Windows\Fonts\msyh.ttc", | |
| r"C:\Windows\Fonts\simsun.ttc", | |
| # Hugging Face Spaces / Linux | |
| "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", | |
| "/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf", | |
| "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", | |
| ] | |
| for font_path in candidate_fonts: | |
| if os.path.exists(font_path): | |
| try: | |
| pdfmetrics.registerFont(TTFont(font_name, font_path)) | |
| print(f"已加载中文字体:{font_path}") | |
| return font_name | |
| except Exception as exc: | |
| print(f"字体加载失败:{font_path},原因:{exc}") | |
| try: | |
| fallback_font = "STSong-Light" | |
| pdfmetrics.registerFont(UnicodeCIDFont(fallback_font)) | |
| print("警告:未找到系统中文字体,已回退到 STSong-Light。") | |
| return fallback_font | |
| except Exception: | |
| print("警告:中文字体加载失败,PDF 可能仍然乱码。") | |
| return "Helvetica" | |
| def build_styles(font_name: str) -> Dict[str, ParagraphStyle]: | |
| styles = getSampleStyleSheet() | |
| base = ParagraphStyle( | |
| "BaseCN", | |
| parent=styles["Normal"], | |
| fontName=font_name, | |
| fontSize=10.5, | |
| leading=17, | |
| alignment=TA_LEFT, | |
| spaceAfter=6, | |
| ) | |
| return { | |
| "title": ParagraphStyle( | |
| "TitleCN", | |
| parent=base, | |
| fontSize=20, | |
| leading=26, | |
| alignment=TA_CENTER, | |
| spaceAfter=18, | |
| ), | |
| "h1": ParagraphStyle( | |
| "H1CN", | |
| parent=base, | |
| fontSize=16, | |
| leading=22, | |
| spaceBefore=14, | |
| spaceAfter=10, | |
| ), | |
| "h2": ParagraphStyle( | |
| "H2CN", | |
| parent=base, | |
| fontSize=13, | |
| leading=20, | |
| spaceBefore=10, | |
| spaceAfter=8, | |
| ), | |
| "h3": ParagraphStyle( | |
| "H3CN", | |
| parent=base, | |
| fontSize=11.5, | |
| leading=18, | |
| spaceBefore=8, | |
| spaceAfter=6, | |
| ), | |
| "body": base, | |
| "bullet": ParagraphStyle( | |
| "BulletCN", | |
| parent=base, | |
| leftIndent=16, | |
| firstLineIndent=-8, | |
| ), | |
| "code": ParagraphStyle( | |
| "CodeCN", | |
| parent=base, | |
| fontName=font_name, | |
| fontSize=8.5, | |
| leading=12, | |
| leftIndent=8, | |
| rightIndent=8, | |
| backColor=colors.whitesmoke, | |
| borderColor=colors.lightgrey, | |
| borderWidth=0.5, | |
| borderPadding=6, | |
| ), | |
| "footer": ParagraphStyle( | |
| "FooterCN", | |
| parent=base, | |
| fontSize=8, | |
| leading=11, | |
| alignment=TA_CENTER, | |
| textColor=colors.grey, | |
| ), | |
| } | |
| def clean_inline_markdown(text: str) -> str: | |
| """把常见 Markdown 内联语法转换为 ReportLab Paragraph 支持的简单标签。""" | |
| text = escape(text) | |
| text = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", text) | |
| # 不再使用 Courier,避免中文行内代码乱码 | |
| text = re.sub(r"`(.+?)`", r"<b>\1</b>", text) | |
| # Markdown 链接 [text](url) -> text(url) | |
| text = re.sub(r"\[(.*?)\]\((.*?)\)", r"\1(\2)", text) | |
| return text | |
| def markdown_to_flowables(markdown_text: str, styles: Dict[str, ParagraphStyle]) -> List[Any]: | |
| """轻量 Markdown 渲染器:支持标题、段落、列表、代码块、简单表格。""" | |
| flowables: List[Any] = [] | |
| lines = markdown_text.replace("\r\n", "\n").split("\n") | |
| in_code = False | |
| code_lines: List[str] = [] | |
| paragraph_lines: List[str] = [] | |
| table_lines: List[str] = [] | |
| def flush_paragraph() -> None: | |
| nonlocal paragraph_lines | |
| if paragraph_lines: | |
| text = " ".join(line.strip() for line in paragraph_lines if line.strip()) | |
| if text: | |
| flowables.append(Paragraph(clean_inline_markdown(text), styles["body"])) | |
| flowables.append(Spacer(1, 0.08 * cm)) | |
| paragraph_lines = [] | |
| def flush_code() -> None: | |
| nonlocal code_lines | |
| if code_lines: | |
| code_text = "\n".join(code_lines) | |
| flowables.append(Preformatted(code_text, styles["code"])) | |
| flowables.append(Spacer(1, 0.12 * cm)) | |
| code_lines = [] | |
| def flush_table() -> None: | |
| nonlocal table_lines | |
| if not table_lines: | |
| return | |
| rows = [] | |
| for line in table_lines: | |
| if re.match(r"^\s*\|?\s*:?-{3,}:?\s*", line): | |
| continue | |
| cells = [clean_inline_markdown(c.strip()) for c in line.strip().strip("|").split("|")] | |
| if cells and any(cells): | |
| rows.append([Paragraph(c, styles["body"]) for c in cells]) | |
| if rows: | |
| table = Table(rows, hAlign="LEFT") | |
| table.setStyle( | |
| TableStyle( | |
| [ | |
| ("GRID", (0, 0), (-1, -1), 0.3, colors.lightgrey), | |
| ("BACKGROUND", (0, 0), (-1, 0), colors.whitesmoke), | |
| ("VALIGN", (0, 0), (-1, -1), "TOP"), | |
| ("LEFTPADDING", (0, 0), (-1, -1), 4), | |
| ("RIGHTPADDING", (0, 0), (-1, -1), 4), | |
| ("TOPPADDING", (0, 0), (-1, -1), 4), | |
| ("BOTTOMPADDING", (0, 0), (-1, -1), 4), | |
| ] | |
| ) | |
| ) | |
| flowables.append(table) | |
| flowables.append(Spacer(1, 0.12 * cm)) | |
| table_lines = [] | |
| for raw_line in lines: | |
| line = raw_line.rstrip() | |
| if line.strip().startswith("```"): | |
| flush_paragraph() | |
| flush_table() | |
| if in_code: | |
| flush_code() | |
| in_code = False | |
| else: | |
| in_code = True | |
| continue | |
| if in_code: | |
| code_lines.append(line) | |
| continue | |
| # 表格行 | |
| if "|" in line and line.strip().startswith("|"): | |
| flush_paragraph() | |
| table_lines.append(line) | |
| continue | |
| else: | |
| flush_table() | |
| if not line.strip(): | |
| flush_paragraph() | |
| continue | |
| if line.startswith("# "): | |
| flush_paragraph() | |
| title = line[2:].strip() | |
| flowables.append(Paragraph(clean_inline_markdown(title), styles["title"])) | |
| continue | |
| if line.startswith("## "): | |
| flush_paragraph() | |
| title = line[3:].strip() | |
| flowables.append(Paragraph(clean_inline_markdown(title), styles["h1"])) | |
| continue | |
| if line.startswith("### "): | |
| flush_paragraph() | |
| title = line[4:].strip() | |
| flowables.append(Paragraph(clean_inline_markdown(title), styles["h2"])) | |
| continue | |
| if line.startswith("#### "): | |
| flush_paragraph() | |
| title = line[5:].strip() | |
| flowables.append(Paragraph(clean_inline_markdown(title), styles["h3"])) | |
| continue | |
| bullet_match = re.match(r"^\s*[-*+]\s+(.+)$", line) | |
| number_match = re.match(r"^\s*\d+[.)]\s+(.+)$", line) | |
| if bullet_match or number_match: | |
| flush_paragraph() | |
| content = bullet_match.group(1) if bullet_match else number_match.group(1) | |
| bullet = "• " if bullet_match else "- " | |
| flowables.append(Paragraph(bullet + clean_inline_markdown(content), styles["bullet"])) | |
| continue | |
| paragraph_lines.append(line) | |
| flush_paragraph() | |
| flush_table() | |
| if in_code: | |
| flush_code() | |
| return flowables | |
| def add_page_number(canvas, doc) -> None: # type: ignore[no-untyped-def] | |
| canvas.saveState() | |
| canvas.setFont("Helvetica", 8) | |
| page_text = f"Page {doc.page}" | |
| canvas.drawRightString(A4[0] - 2 * cm, 1.2 * cm, page_text) | |
| canvas.restoreState() | |
| def create_pdf(markdown_text: str, filename_prefix: str = "agent_report") -> str: | |
| """第四阶段:生成 PDF 文件。""" | |
| font_name = register_chinese_font() | |
| styles = build_styles(font_name) | |
| timestamp = dt.datetime.now().strftime("%Y%m%d_%H%M%S") | |
| pdf_path = OUTPUT_DIR / f"{filename_prefix}_{timestamp}_{uuid.uuid4().hex[:6]}.pdf" | |
| doc = SimpleDocTemplate( | |
| str(pdf_path), | |
| pagesize=A4, | |
| rightMargin=2 * cm, | |
| leftMargin=2 * cm, | |
| topMargin=1.8 * cm, | |
| bottomMargin=1.8 * cm, | |
| title="通用问题优化智能体求解报告", | |
| ) | |
| flowables = markdown_to_flowables(markdown_text, styles) | |
| if not flowables: | |
| flowables = [Paragraph("未生成有效报告内容。", styles["body"])] | |
| doc.build(flowables, onFirstPage=add_page_number, onLaterPages=add_page_number) | |
| return str(pdf_path) | |
| def run_agent(user_question: str, max_results: int) -> Tuple[Dict[str, Any], str, str, str, str]: | |
| """Gradio 主流程。""" | |
| if not user_question or not user_question.strip(): | |
| return {}, "", "", None, "请输入需要求解的问题。" # type: ignore[return-value] | |
| try: | |
| # 1. 问题优化 | |
| optimized = optimize_question(user_question.strip()) | |
| # 2. 联网搜索 | |
| search_query = optimized.get("search_query") or user_question.strip() | |
| search_items, search_status = search_web(str(search_query), max_results=max_results) | |
| search_text = format_search_results(search_items, search_status) | |
| # 3. 综合求解并生成 Markdown 报告 | |
| report_md = generate_report(user_question.strip(), optimized, search_text) | |
| # 4. 生成 PDF | |
| pdf_path = create_pdf(report_md) | |
| status = "运行完成:已完成问题优化、联网搜索、综合求解,并生成 PDF 报告。" | |
| return optimized, search_text, report_md, pdf_path, status | |
| except Exception as exc: | |
| error_detail = traceback.format_exc() | |
| status = f"运行失败:{exc}\n\n调试信息:\n{error_detail}" | |
| return {}, "", "", None, status # type: ignore[return-value] | |
| EXAMPLE_QUESTIONS = [ | |
| "我想用大模型智能体完成课程大作业,但现在只有一个简单想法,不知道怎么设计系统、怎么展示效果、怎么写提交材料,请帮我优化这个问题并给出完整方案,最后生成PDF报告。", | |
| "我想准备一次关于大语言模型内部激活探测技术的课程展示,请帮我优化问题、搜索资料并输出报告。", | |
| "我想学习线性规划中的对偶问题,但我基础比较薄弱,请帮我把问题改写清楚并给出适合开卷考试的解题步骤。", | |
| ] | |
| def build_demo() -> gr.Blocks: | |
| with gr.Blocks(title="通用问题优化与求解智能体") as demo: | |
| gr.Markdown( | |
| """ | |
| # 通用问题优化与求解智能体 | |
| 输入一个原始问题,智能体会自动完成:**问题分析 → Prompt 优化 → 联网搜索 → 综合求解 → PDF 报告生成**。 | |
| 适合用于课程大作业演示:公开视频链接、MP4 录屏、PDF 报告都可以从这里完成。 | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| question = gr.Textbox( | |
| label="用户原始问题", | |
| placeholder="请输入一个模糊或复杂的问题,例如:我想完成一个大模型智能体课程作业,但不知道怎么设计系统……", | |
| lines=7, | |
| ) | |
| max_results = gr.Slider( | |
| minimum=0, | |
| maximum=10, | |
| value=DEFAULT_MAX_RESULTS, | |
| step=1, | |
| label="联网搜索结果数量。设置为 0 可跳过搜索。", | |
| ) | |
| run_btn = gr.Button("开始优化并求解", variant="primary") | |
| gr.Examples( | |
| examples=EXAMPLE_QUESTIONS, | |
| inputs=question, | |
| label="示例问题", | |
| ) | |
| with gr.Column(scale=1): | |
| status = gr.Textbox(label="运行状态", lines=10) | |
| pdf_file = gr.File(label="下载 PDF 报告") | |
| with gr.Tab("1. 问题优化结果"): | |
| optimized_json = gr.JSON(label="结构化问题优化结果") | |
| with gr.Tab("2. 联网搜索结果"): | |
| search_output = gr.Textbox(label="搜索结果", lines=18) | |
| with gr.Tab("3. 最终 Markdown 报告"): | |
| report_output = gr.Markdown(label="报告预览") | |
| run_btn.click( | |
| fn=run_agent, | |
| inputs=[question, max_results], | |
| outputs=[optimized_json, search_output, report_output, pdf_file, status], | |
| ) | |
| return demo | |
| if __name__ == "__main__": | |
| demo = build_demo() | |
| share = os.getenv("GRADIO_SHARE", "false").lower() in {"1", "true", "yes"} | |
| port = int(os.getenv("PORT", "7860")) | |
| demo.launch(server_name="0.0.0.0", server_port=port, share=share) | |