MarioPrzBasto commited on
Commit
f87d9f1
·
verified ·
1 Parent(s): 3065d4e

Update similarity.py (#6)

Browse files

- Update similarity.py (24e1c6ada9903aaf125e34b5b82c83b8ae3c0e7b)

Files changed (1) hide show
  1. similarity.py +81 -11
similarity.py CHANGED
@@ -73,20 +73,90 @@ def ssim_sim(img1, img2):
73
  return (s + 1) * 50
74
 
75
 
76
- def load_image_url(source):
77
  Image.MAX_IMAGE_PIXELS = None
78
 
79
- if source.startswith('http'):
80
- response = requests.get(source)
81
- img = np.asarray(bytearray(response.content), dtype=np.uint8)
82
- img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
83
- else:
84
- img = base64.b64decode(source)
85
- img = Image.open(BytesIO(img))
86
- img = np.array(img)
87
- img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
- return img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  def check_similarity(images: List[RequestModel]):
92
  logging.info(f"Checking similarity for main source with resource id {images[0].originId}")
 
73
  return (s + 1) * 50
74
 
75
 
76
+ def load_image(source, assetCode, contentType=None, ffmpeg_path='ffmpeg', frame_time=1):
77
  Image.MAX_IMAGE_PIXELS = None
78
 
79
+ def extract_frame_from_video(video_path_or_url, time_sec):
80
+ print(f"[INFO] A extrair frame do vídeo: {video_path_or_url} no segundo {time_sec}")
81
+
82
+ with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as temp_frame:
83
+ frame_path = temp_frame.name
84
+
85
+ command = [
86
+ ffmpeg_path,
87
+ "-ss", str(time_sec),
88
+ "-i", video_path_or_url,
89
+ "-frames:v", "1",
90
+ "-q:v", "2",
91
+ "-y",
92
+ frame_path
93
+ ]
94
+
95
+ print(f"[DEBUG] Comando ffmpeg: {' '.join(command)}")
96
+
97
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
98
+
99
+ if result.returncode != 0:
100
+ print(f"[ERRO] ffmpeg falhou com código {result.returncode}")
101
+ print(f"[ERRO] stderr: {result.stderr.decode('utf-8')}")
102
+ raise RuntimeError("Erro ao extrair frame com ffmpeg.")
103
+
104
+ if not os.path.exists(frame_path):
105
+ print("[ERRO] Frame não criado. Verifica se o caminho do vídeo está correto e acessível.")
106
+ raise ValueError("Frame não encontrado após execução do ffmpeg.")
107
 
108
+ frame = cv2.imread(frame_path, cv2.IMREAD_GRAYSCALE)
109
+ os.remove(frame_path)
110
+
111
+ if frame is None:
112
+ print("[ERRO] Falha ao ler frame extraído com OpenCV.")
113
+ raise ValueError("Erro ao carregar frame extraído.")
114
+
115
+ print(f"[SUCESSO] Frame extraído com sucesso de {video_path_or_url}")
116
+ return frame
117
+
118
+ try:
119
+ if source.startswith('http'):
120
+ print(f"[INFO] Content-Type de {assetCode} é {contentType}")
121
+
122
+ if contentType and contentType.startswith('video'):
123
+ return extract_frame_from_video(source, frame_time)
124
+
125
+ print(f"[INFO] A carregar imagem {assetCode} a partir de URL")
126
+ response = requests.get(source)
127
+ img = np.asarray(bytearray(response.content), dtype=np.uint8)
128
+ img = cv2.imdecode(img, cv2.IMREAD_GRAYSCALE)
129
+ return img
130
+
131
+ else:
132
+ print(f"[INFO] A tentar carregar base64 de {assetCode} como imagem ou vídeo.")
133
+
134
+ try:
135
+ img_bytes = base64.b64decode(source)
136
+
137
+ if contentType and contentType.startswith('image'):
138
+ print(f"[INFO] Base64 de {assetCode} identificado como imagem")
139
+ img = Image.open(BytesIO(img_bytes))
140
+ img = np.array(img)
141
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
142
+ return img
143
+ else:
144
+ print(f"[INFO] Base64 de {assetCode} identificado como vídeo")
145
+ with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
146
+ temp_video.write(img_bytes)
147
+ temp_video_path = temp_video.name
148
+
149
+ frame = extract_frame_from_video(temp_video_path, frame_time)
150
+ os.remove(temp_video_path)
151
+ return frame
152
+
153
+ except Exception as e:
154
+ print(f"[ERRO] Falha ao processar base64 de {assetCode}: {e}")
155
+ raise
156
+
157
+ except Exception as e:
158
+ print(f"[ERRO] Falha ao carregar imagem para {assetCode}: {e}")
159
+ return None
160
 
161
  def check_similarity(images: List[RequestModel]):
162
  logging.info(f"Checking similarity for main source with resource id {images[0].originId}")