Sheldon Zheng commited on
Commit
ca9ebec
·
1 Parent(s): 2704677

fix: move orjson block after gradio import to avoid breaking gradio

Browse files

Gradio itself imports orjson at gradio/utils.py:52. Blocking orjson
before importing gradio causes ModuleNotFoundError crash.

Move sys.modules["orjson"] = None to AFTER import gradio. Gradio's
existing reference to orjson (already bound in module namespace) is
unaffected. Plotly's get_module("orjson") dynamically queries
sys.modules and will now get None, falling back to standard json.

Files changed (1) hide show
  1. app.py +8 -9
app.py CHANGED
@@ -6,15 +6,6 @@ Rural Low-Voltage Distribution Network Voltage Anomaly Detection Demo
6
  HuggingFace Spaces 版本
7
  """
8
 
9
- # ── 必须在所有其他 import 之前: 屏蔽 orjson ──
10
- # Plotly 6.x + orjson 会将 numpy 数组序列化为 bdata (base64 二进制)。
11
- # Gradio 4.44.1 内置的 Plotly.js 无法解析 bdata,导致图表不渲染。
12
- # 在 sys.modules 中设置 orjson=None,Python 对 import orjson 将抛出 ImportError,
13
- # 迫使 Plotly 回退到标准 json 引擎 (numpy → list)。
14
- import sys as _sys
15
- _sys.modules["orjson"] = None
16
- # ── End orjson block ──
17
-
18
  # ── Monkey-patch: 修复 gradio_client 处理 additionalProperties: true 的 bug ──
19
  # gradio_client/utils.py 中 _json_schema_to_python_type 无法处理布尔值 schema,
20
  # 当 JSON Schema 包含 "additionalProperties": true 时会触发
@@ -36,6 +27,14 @@ import gradio as gr
36
  import sys
37
  from pathlib import Path
38
 
 
 
 
 
 
 
 
 
39
  # 添加项目路径 (HuggingFace Spaces 兼容)
40
  DEMO_DIR = Path(__file__).parent
41
  sys.path.insert(0, str(DEMO_DIR))
 
6
  HuggingFace Spaces 版本
7
  """
8
 
 
 
 
 
 
 
 
 
 
9
  # ── Monkey-patch: 修复 gradio_client 处理 additionalProperties: true 的 bug ──
10
  # gradio_client/utils.py 中 _json_schema_to_python_type 无法处理布尔值 schema,
11
  # 当 JSON Schema 包含 "additionalProperties": true 时会触发
 
27
  import sys
28
  from pathlib import Path
29
 
30
+ # ── 屏蔽 Plotly 使用 orjson (必须在 import gradio 之后) ──
31
+ # Gradio 在 utils.py:52 直接 import orjson,所以不能在导入前屏蔽。
32
+ # 但 Gradio 导入后 orjson 已绑定到 gradio.utils.orjson,修改 sys.modules 不影响它。
33
+ # Plotly 6.x 在每次序列化时通过 get_module("orjson") 动态查询 sys.modules,
34
+ # 设为 None 后 get_module 返回 None,Plotly 回退到标准 json 引擎 (无 bdata)。
35
+ sys.modules["orjson"] = None
36
+ # ── End orjson block ──
37
+
38
  # 添加项目路径 (HuggingFace Spaces 兼容)
39
  DEMO_DIR = Path(__file__).parent
40
  sys.path.insert(0, str(DEMO_DIR))