OpenIPOS commited on
Commit
37bc75f
·
verified ·
1 Parent(s): 9cb9202

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -34
app.py CHANGED
@@ -1,54 +1,88 @@
1
  import gradio as gr
2
  import torch
3
- from transformers import AutoTokenizer, AutoModel
4
  import numpy as np
 
5
 
6
- # 1. 加载谷歌专利专用 BERT (0.3B 极其轻量)
7
  model_name = "anferico/bert-for-patents"
8
- tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False)
9
- model = AutoModel.from_pretrained(model_name)
 
 
 
 
 
 
 
 
 
10
 
11
  def get_embedding(text):
12
- # 将文本转化为 1024 维的专利语义向量
13
- inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
14
- with torch.no_grad():
15
- outputs = model(**inputs)
16
- # 取最后一层隐藏状态的平均值作为特征向量 (Mean Pooling)
17
- embeddings = outputs.last_hidden_state.mean(dim=1).squeeze().numpy()
18
- return embeddings.tolist()
 
 
 
 
 
19
 
20
  def compute_similarity(text1, text2):
21
- # 计算两个专利描述之间的语义相似度 (余弦相似度)
22
- v1 = np.array(get_embedding(text1))
23
- v2 = np.array(get_embedding(text2))
24
- similarity = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
25
- return f"{similarity:.4f}"
 
 
 
 
 
26
 
27
- # 2. 界面装修:走 OpenIPOS 旗舰风格
28
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
29
  gr.HTML("""
30
  <div style="display: flex; align-items: center; gap: 20px; padding: 10px;">
31
- <img src="https://s3.bmp.ovh/2026/03/30/rIAGKg0O.png" style="height: 50px;">
32
  <div>
33
- <h1 style="margin:0;">OpenIPOS Patent Vector Engine</h1>
34
- <p style="margin:0; color:#666;">基于 BERT-for-Patents 的专业专利语义标尺 (0.3B)</p>
35
  </div>
36
  </div>
37
  """)
38
 
39
- with gr.Tab("语义相似度比对"):
40
- t1 = gr.Textbox(label="技术特征 A (或权利要求 1)", placeholder="例如:一种含有纳米材料的涂层...")
41
- t2 = gr.Textbox(label="技术特征 B (或对比文件 D1)", placeholder="例如:一种表面处理工艺,包含特殊涂层...")
42
- btn = gr.Button("开始比对", variant="primary")
43
- out = gr.Label(label="语义重合度 (0-1)")
44
- btn.click(compute_similarity, inputs=[t1, t2], outputs=out)
45
-
46
- with gr.Tab("向量化测试 (API 用)"):
47
- input_text = gr.Textbox(label="输入专利文本")
48
- vector_out = gr.JSON(label="生成的 1024 维特征向量")
49
- v_btn = gr.Button("生成向量")
50
- v_btn.click(get_embedding, inputs=input_text, outputs=vector_out)
51
-
52
- gr.Markdown("> **提示**:该 Space 已自动开启 API 访问。你可以将此 URL 对接到 Dify 的自定义算子中,作为专利检索的 Embedding 引擎。")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
 
54
  demo.launch()
 
1
  import gradio as gr
2
  import torch
 
3
  import numpy as np
4
+ from transformers import BertTokenizer, BertModel
5
 
6
+ # 1. 核心引擎加载:强制使用慢速分词模式以兼容专利模型
7
  model_name = "anferico/bert-for-patents"
8
+
9
+ print("正在加载专利专用分词器...")
10
+ tokenizer = BertTokenizer.from_pretrained(
11
+ model_name,
12
+ use_fast=False,
13
+ local_files_only=False
14
+ )
15
+
16
+ print("正在加载 BERT 专利模型主体 (0.3B)...")
17
+ model = BertModel.from_pretrained(model_name)
18
+ model.eval() # 设置为评估模式
19
 
20
  def get_embedding(text):
21
+ if not text.strip():
22
+ return [0] * 1024
23
+ try:
24
+ # 将文本转化为 1024 维的专利语义向量
25
+ inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
26
+ with torch.no_grad():
27
+ outputs = model(**inputs)
28
+ # 取最后一层隐藏状态的平均值作为特征向量 (Mean Pooling)
29
+ embeddings = outputs.last_hidden_state.mean(dim=1).squeeze().numpy()
30
+ return embeddings.tolist()
31
+ except Exception as e:
32
+ return f"向量化错误: {str(e)}"
33
 
34
  def compute_similarity(text1, text2):
35
+ if not text1.strip() or not text2.strip():
36
+ return "请输入完整的对比文本"
37
+ try:
38
+ v1 = np.array(get_embedding(text1))
39
+ v2 = np.array(get_embedding(text2))
40
+ # 计算余弦相似度
41
+ similarity = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
42
+ return f"{similarity:.4f}"
43
+ except Exception as e:
44
+ return f"计算失败: {str(e)}"
45
 
46
+ # 2. OpenIPOS 旗舰版界面装修
47
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
48
  gr.HTML("""
49
  <div style="display: flex; align-items: center; gap: 20px; padding: 10px;">
50
+ <img src="https://s3.bmp.ovh/2026/03/30/rIAGKg0O.png" style="height: 50px; width: auto;">
51
  <div>
52
+ <h1 style="margin: 0; font-size: 24px;">OpenIPOS Patent Vector Engine</h1>
53
+ <p style="margin: 0; color: #666;">基于谷歌 BERT-for-Patents 的专业语义标尺 (0.3B)</p>
54
  </div>
55
  </div>
56
  """)
57
 
58
+ with gr.Tabs():
59
+ with gr.TabItem("🔍 语义相似度比对"):
60
+ with gr.Row():
61
+ with gr.Column():
62
+ t1 = gr.Textbox(label="本申请技术特征 (权利要求)", lines=8, placeholder="请输入权利要求书中的核心技术特征...")
63
+ with gr.Column():
64
+ t2 = gr.Textbox(label="对比文件技术特征 (D1/D2)", lines=8, placeholder="请输入对比文件中的对应描述内容...")
65
+
66
+ compare_btn = gr.Button("开始语义比对", variant="primary")
67
+ similarity_output = gr.Label(label="语义重合度评分 (0-1)")
68
+
69
+ gr.Markdown("""
70
+ ### ⚖️ 判读参考:
71
+ * **0.85 - 1.00**:极高风险。语义高度重合,可能构成实质性相同。
72
+ * **0.70 - 0.85**:高风险。核心特征重叠,建议重点修改权利要求。
73
+ * **0.50 - 0.70**:中等风险。存在语义关联,具有一定的创造性抗辩空间。
74
+ """)
75
+
76
+ compare_btn.click(compute_similarity, inputs=[t1, t2], outputs=similarity_output)
77
+
78
+ with gr.TabItem("📊 向量化测试 (API)"):
79
+ input_text = gr.Textbox(label="输入专利描述", lines=5)
80
+ v_btn = gr.Button("生成 1024 维特征向量")
81
+ vector_out = gr.JSON(label="向量数组")
82
+ v_btn.click(get_embedding, inputs=input_text, outputs=vector_out)
83
+
84
+ gr.Markdown("---")
85
+ gr.Markdown("© 2026 OpenIPOS Global Limited. 核心算法:BERT for Patents | 算力驱动:Hugging Face CPU Basic")
86
 
87
+ # 启动
88
  demo.launch()