Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
Update similarity.py
Browse files- similarity.py +15 -17
similarity.py
CHANGED
@@ -45,7 +45,7 @@ def mobilenet_sim(img1, img2, img1AssetCode, img2AssetCode):
|
|
45 |
|
46 |
sim = cosine_similarity(feat1, feat2)[0][0]
|
47 |
sim_score = (sim + 1) * 50
|
48 |
-
|
49 |
return float(sim_score)
|
50 |
except Exception as e:
|
51 |
logging.error("Erro ao calcular similaridade com MobileNet", exc_info=True)
|
@@ -79,9 +79,7 @@ def ssim_sim(img1, img2):
|
|
79 |
def load_image_url(source, assetCode, contentType=None, ffmpeg_path='ffmpeg', frame_time=1):
|
80 |
Image.MAX_IMAGE_PIXELS = None
|
81 |
|
82 |
-
def extract_frame_from_video(video_path_or_url, time_sec):
|
83 |
-
print(f"[INFO] A extrair frame do vídeo: {video_path_or_url} no segundo {time_sec}")
|
84 |
-
|
85 |
with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as temp_frame:
|
86 |
frame_path = temp_frame.name
|
87 |
|
@@ -95,50 +93,50 @@ def load_image_url(source, assetCode, contentType=None, ffmpeg_path='ffmpeg', fr
|
|
95 |
frame_path
|
96 |
]
|
97 |
|
98 |
-
|
99 |
|
100 |
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
101 |
|
102 |
if result.returncode != 0:
|
103 |
-
|
104 |
-
|
105 |
raise RuntimeError("Erro ao extrair frame com ffmpeg.")
|
106 |
|
107 |
if not os.path.exists(frame_path):
|
108 |
-
|
109 |
raise ValueError("Frame não encontrado após execução do ffmpeg.")
|
110 |
|
111 |
frame = cv2.imread(frame_path, cv2.IMREAD_GRAYSCALE)
|
112 |
os.remove(frame_path)
|
113 |
|
114 |
if frame is None:
|
115 |
-
|
116 |
raise ValueError("Erro ao carregar frame extraído.")
|
117 |
|
118 |
-
|
119 |
return frame
|
120 |
|
121 |
try:
|
122 |
if source.startswith('http'):
|
123 |
-
|
124 |
|
125 |
if contentType and contentType.startswith('video'):
|
126 |
return extract_frame_from_video(source, frame_time)
|
127 |
|
128 |
-
|
129 |
response = requests.get(source)
|
130 |
img = np.asarray(bytearray(response.content), dtype=np.uint8)
|
131 |
img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
|
132 |
return img
|
133 |
|
134 |
else:
|
135 |
-
|
136 |
|
137 |
try:
|
138 |
img_bytes = base64.b64decode(source)
|
139 |
|
140 |
if contentType and contentType.startswith('video'):
|
141 |
-
|
142 |
with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
|
143 |
temp_video.write(img_bytes)
|
144 |
temp_video_path = temp_video.name
|
@@ -147,7 +145,7 @@ def load_image_url(source, assetCode, contentType=None, ffmpeg_path='ffmpeg', fr
|
|
147 |
os.remove(temp_video_path)
|
148 |
return frame
|
149 |
else:
|
150 |
-
|
151 |
img = Image.open(BytesIO(img_bytes))
|
152 |
img = np.array(img)
|
153 |
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
@@ -155,11 +153,11 @@ def load_image_url(source, assetCode, contentType=None, ffmpeg_path='ffmpeg', fr
|
|
155 |
|
156 |
|
157 |
except Exception as e:
|
158 |
-
|
159 |
raise
|
160 |
|
161 |
except Exception as e:
|
162 |
-
|
163 |
return None
|
164 |
|
165 |
def check_similarity(images: List[RequestModel]):
|
|
|
45 |
|
46 |
sim = cosine_similarity(feat1, feat2)[0][0]
|
47 |
sim_score = (sim + 1) * 50
|
48 |
+
logging.info(f"MobileNet similarity score from {img1AssetCode} and {img2AssetCode} is {sim_score}")
|
49 |
return float(sim_score)
|
50 |
except Exception as e:
|
51 |
logging.error("Erro ao calcular similaridade com MobileNet", exc_info=True)
|
|
|
79 |
def load_image_url(source, assetCode, contentType=None, ffmpeg_path='ffmpeg', frame_time=1):
|
80 |
Image.MAX_IMAGE_PIXELS = None
|
81 |
|
82 |
+
def extract_frame_from_video(video_path_or_url, time_sec):
|
|
|
|
|
83 |
with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as temp_frame:
|
84 |
frame_path = temp_frame.name
|
85 |
|
|
|
93 |
frame_path
|
94 |
]
|
95 |
|
96 |
+
logging.info(f"[DEBUG] Comando ffmpeg: {' '.join(command)}")
|
97 |
|
98 |
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
99 |
|
100 |
if result.returncode != 0:
|
101 |
+
logging.error(f"[ERRO] ffmpeg falhou com código {result.returncode}")
|
102 |
+
logging.error(f"[ERRO] stderr: {result.stderr.decode('utf-8')}")
|
103 |
raise RuntimeError("Erro ao extrair frame com ffmpeg.")
|
104 |
|
105 |
if not os.path.exists(frame_path):
|
106 |
+
logging.error("[ERRO] Frame não criado. Verifica se o caminho do vídeo está correto e acessível.")
|
107 |
raise ValueError("Frame não encontrado após execução do ffmpeg.")
|
108 |
|
109 |
frame = cv2.imread(frame_path, cv2.IMREAD_GRAYSCALE)
|
110 |
os.remove(frame_path)
|
111 |
|
112 |
if frame is None:
|
113 |
+
logging.error("[ERRO] Falha ao ler frame extraído com OpenCV.")
|
114 |
raise ValueError("Erro ao carregar frame extraído.")
|
115 |
|
116 |
+
logging.info(f"[SUCESSO] Frame extraído com sucesso de {video_path_or_url}")
|
117 |
return frame
|
118 |
|
119 |
try:
|
120 |
if source.startswith('http'):
|
121 |
+
logging.info(f"[INFO] Content-Type de {assetCode} é {contentType}")
|
122 |
|
123 |
if contentType and contentType.startswith('video'):
|
124 |
return extract_frame_from_video(source, frame_time)
|
125 |
|
126 |
+
logging.info(f"[INFO] A carregar imagem {assetCode} a partir de URL")
|
127 |
response = requests.get(source)
|
128 |
img = np.asarray(bytearray(response.content), dtype=np.uint8)
|
129 |
img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
|
130 |
return img
|
131 |
|
132 |
else:
|
133 |
+
logging.info(f"[INFO] A tentar carregar base64 de {assetCode} como imagem ou vídeo.")
|
134 |
|
135 |
try:
|
136 |
img_bytes = base64.b64decode(source)
|
137 |
|
138 |
if contentType and contentType.startswith('video'):
|
139 |
+
logging.info(f"[INFO] Base64 de {assetCode} identificado como vídeo")
|
140 |
with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
|
141 |
temp_video.write(img_bytes)
|
142 |
temp_video_path = temp_video.name
|
|
|
145 |
os.remove(temp_video_path)
|
146 |
return frame
|
147 |
else:
|
148 |
+
logging.info(f"[INFO] Base64 de {assetCode} identificado como imagem")
|
149 |
img = Image.open(BytesIO(img_bytes))
|
150 |
img = np.array(img)
|
151 |
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
|
|
153 |
|
154 |
|
155 |
except Exception as e:
|
156 |
+
logging.info(f"[ERRO] Falha ao processar base64 de {assetCode}: {e}")
|
157 |
raise
|
158 |
|
159 |
except Exception as e:
|
160 |
+
logging.info(f"[ERRO] Falha ao carregar imagem para {assetCode}: {e}")
|
161 |
return None
|
162 |
|
163 |
def check_similarity(images: List[RequestModel]):
|