OpenIPOS commited on
Commit
bb11689
·
verified ·
1 Parent(s): d813dfc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -6
app.py CHANGED
@@ -1,10 +1,54 @@
1
  import gradio as gr
 
 
 
2
 
3
- with gr.Blocks(fill_height=True) as demo:
4
- with gr.Sidebar():
5
- gr.Markdown("# Inference Provider")
6
- gr.Markdown("This Space showcases the anferico/bert-for-patents model, served by the hf-inference API. Sign in with your Hugging Face account to use this API.")
7
- button = gr.LoginButton("Sign in")
8
- gr.load("models/anferico/bert-for-patents", accept_token=button, provider="hf-inference")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  demo.launch()
 
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)
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()