svjack commited on
Commit
6d656a7
·
verified ·
1 Parent(s): 27279d0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import snapshot_download
2
+ from insightface.app import FaceAnalysis
3
+ import numpy as np
4
+ import cv2
5
+ import gradio as gr
6
+
7
+ # 下载模型
8
+ snapshot_download(
9
+ "fal/AuraFace-v1",
10
+ local_dir="models/auraface",
11
+ )
12
+
13
+ # 初始化FaceAnalysis
14
+ face_app = FaceAnalysis(
15
+ name="auraface",
16
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
17
+ root=".",
18
+ )
19
+
20
+ def get_embedding(image):
21
+ # 将图片转换为OpenCV格式
22
+ cv2_image = np.array(image.convert("RGB"))
23
+ cv2_image = cv2_image[:, :, ::-1]
24
+
25
+ # 获取人脸嵌入
26
+ faces = face_app.get(cv2_image)
27
+ if len(faces) > 0:
28
+ return faces[0].normed_embedding
29
+ else:
30
+ return None
31
+
32
+ def calculate_similarity(image1, image2):
33
+ # 获取两张图片的嵌入
34
+ embedding1 = get_embedding(image1)
35
+ embedding2 = get_embedding(image2)
36
+
37
+ if embedding1 is not None and embedding2 is not None:
38
+ # 计算余弦相似度
39
+ similarity = np.dot(embedding1, embedding2) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding2))
40
+ return f"图片相似度: {similarity:.4f}"
41
+ else:
42
+ return "无法检测到人脸或计算相似度"
43
+
44
+ # 创建Gradio界面
45
+ iface = gr.Interface(
46
+ fn=calculate_similarity,
47
+ inputs=[gr.Image(type="pil"), gr.Image(type="pil")],
48
+ outputs="text",
49
+ title="图片相似度计算",
50
+ description="上传两张图片,计算它们的相似度。"
51
+ )
52
+
53
+ # 启动Gradio应用
54
+ iface.launch(share = True)