Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,7 +9,6 @@ import torch
|
|
| 9 |
from scipy.stats import pearsonr
|
| 10 |
|
| 11 |
# --- MÓDULO DE INICIALIZAÇÃO ---
|
| 12 |
-
# Tenta carregar os modelos e módulos, definindo flags de disponibilidade.
|
| 13 |
CLIP_AVAILABLE, SALIENCY_AVAILABLE = False, False
|
| 14 |
try:
|
| 15 |
from transformers import CLIPProcessor, CLIPModel
|
|
@@ -22,7 +21,6 @@ except Exception as e:
|
|
| 22 |
print(f"AVISO: Modelo CLIP não carregado. Teste de Inteligência desabilitado. Erro: {e}")
|
| 23 |
|
| 24 |
try:
|
| 25 |
-
# A instalação de 'opencv-contrib-python-headless' deve resolver isso.
|
| 26 |
saliency_detector = cv2.saliency.StaticSaliencySpectralResidual_create()
|
| 27 |
SALIENCY_AVAILABLE = True
|
| 28 |
print("Módulo de Saliência carregado com sucesso.")
|
|
@@ -32,32 +30,135 @@ except AttributeError:
|
|
| 32 |
except Exception as e:
|
| 33 |
print(f"AVISO: Módulo de Saliência não carregado. Erro: {e}")
|
| 34 |
|
| 35 |
-
|
| 36 |
-
#
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
# --- FUNÇÃO DE CALLBACK PRINCIPAL ---
|
| 42 |
-
def run_full_analysis(video_path, descriptions_text, progress=gr.Progress
|
| 43 |
-
if video_path is None: raise gr.Error("
|
| 44 |
|
| 45 |
-
# Executa as análises principais que sempre funcionam
|
| 46 |
progress(0, desc="Analisando fidelidade...")
|
| 47 |
-
frames, fps, ssim_scores, phash_distances = analisar_fidelidade(video_path
|
| 48 |
|
|
|
|
| 49 |
fidelidade_plot_path = gerar_grafico_fidelidade(ssim_scores, phash_distances, len(frames), fps)
|
| 50 |
-
cor_plot_path = gerar_grafico_cor_luz(ssim_scores, phash_distances, len(frames), fps) # Supondo que você tenha essa função
|
| 51 |
-
anomalias_plot_path = gerar_grafico_anomalias(ssim_scores, phash_distances, len(frames), fps) # Supondo que você tenha essa função
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
|
|
|
| 56 |
if SALIENCY_AVAILABLE:
|
| 57 |
progress(0.6, desc="Analisando foco móvel...")
|
| 58 |
-
ssim_foco, jitter_foco = analisar_estabilidade_foco(frames
|
| 59 |
-
foco_plot_path =
|
| 60 |
|
|
|
|
| 61 |
if CLIP_AVAILABLE and descriptions_text.strip():
|
| 62 |
progress(0.8, desc="Executando teste semântico...")
|
| 63 |
semantico_path, error_msg = executar_teste_semantico(phash_distances, descriptions_text)
|
|
@@ -68,31 +169,23 @@ def run_full_analysis(video_path, descriptions_text, progress=gr.Progress()):
|
|
| 68 |
# --- INTERFACE GRADIO ---
|
| 69 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 70 |
gr.Markdown("# Suíte de Validação Completa para Geração de Vídeo (ADUC-SDR)")
|
| 71 |
-
|
| 72 |
with gr.Row():
|
| 73 |
with gr.Column(scale=1):
|
| 74 |
video_input = gr.Video(label="1. Upload do vídeo")
|
| 75 |
descriptions_input = gr.Textbox(lines=5, label="2. Descrições (Opcional)", placeholder="Uma descrição por cena...")
|
| 76 |
analyze_button = gr.Button("3. Executar Análise Completa", variant="primary")
|
| 77 |
-
|
| 78 |
with gr.Tabs():
|
| 79 |
with gr.TabItem("1. Fidelidade e Coerência"):
|
| 80 |
plot_fidelidade = gr.Image(label="Gráfico de Análise de Fidelidade (SSIM e pHash)")
|
| 81 |
-
|
| 82 |
with gr.TabItem("2. Cor e Iluminação"):
|
| 83 |
plot_cor = gr.Image(label="Gráfico de Análise de Cor e Luminância")
|
| 84 |
-
|
| 85 |
with gr.TabItem("3. Foco (Vídeo Móvel)"):
|
| 86 |
plot_foco = gr.Image(label="Gráfico de Análise de Foco e Jitter")
|
| 87 |
-
|
| 88 |
with gr.TabItem("4. Glitches de Movimento"):
|
| 89 |
plot_anomalias = gr.Image(label="Gráfico do Detector de Anomalias de Movimento")
|
| 90 |
-
|
| 91 |
with gr.TabItem("5. Inteligência Adaptativa"):
|
| 92 |
plot_semantico = gr.Image(label="Gráfico de Estresse Semântico")
|
| 93 |
|
| 94 |
-
# A interatividade foi removida para garantir que o app inicie
|
| 95 |
-
# O callback do botão agora é mais simples
|
| 96 |
analyze_button.click(
|
| 97 |
fn=run_full_analysis,
|
| 98 |
inputs=[video_input, descriptions_input],
|
|
@@ -100,4 +193,4 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 100 |
)
|
| 101 |
|
| 102 |
if __name__ == "__main__":
|
| 103 |
-
demo.queue().launch(
|
|
|
|
| 9 |
from scipy.stats import pearsonr
|
| 10 |
|
| 11 |
# --- MÓDULO DE INICIALIZAÇÃO ---
|
|
|
|
| 12 |
CLIP_AVAILABLE, SALIENCY_AVAILABLE = False, False
|
| 13 |
try:
|
| 14 |
from transformers import CLIPProcessor, CLIPModel
|
|
|
|
| 21 |
print(f"AVISO: Modelo CLIP não carregado. Teste de Inteligência desabilitado. Erro: {e}")
|
| 22 |
|
| 23 |
try:
|
|
|
|
| 24 |
saliency_detector = cv2.saliency.StaticSaliencySpectralResidual_create()
|
| 25 |
SALIENCY_AVAILABLE = True
|
| 26 |
print("Módulo de Saliência carregado com sucesso.")
|
|
|
|
| 30 |
except Exception as e:
|
| 31 |
print(f"AVISO: Módulo de Saliência não carregado. Erro: {e}")
|
| 32 |
|
| 33 |
+
|
| 34 |
+
# --- FUNÇÕES DE ANÁLISE ---
|
| 35 |
+
|
| 36 |
+
def analisar_fidelidade(video_path):
|
| 37 |
+
cap = cv2.VideoCapture(video_path)
|
| 38 |
+
frames, ssim_scores, phash_distances = [], [], []
|
| 39 |
+
fps = cap.get(cv2.CAP_PROP_FPS) or 30
|
| 40 |
+
|
| 41 |
+
while True:
|
| 42 |
+
ret, frame = cap.read()
|
| 43 |
+
if not ret: break
|
| 44 |
+
frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
| 45 |
+
cap.release()
|
| 46 |
+
|
| 47 |
+
for i in range(len(frames) - 1):
|
| 48 |
+
gray1 = cv2.cvtColor(frames[i], cv2.COLOR_RGB2GRAY)
|
| 49 |
+
gray2 = cv2.cvtColor(frames[i+1], cv2.COLOR_RGB2GRAY)
|
| 50 |
+
ssim_val, _ = ssim(gray1, gray2, full=True, data_range=gray1.max() - gray1.min())
|
| 51 |
+
|
| 52 |
+
pil_img1 = Image.fromarray(frames[i])
|
| 53 |
+
pil_img2 = Image.fromarray(frames[i+1])
|
| 54 |
+
phash_dist = imagehash.phash(pil_img1) - imagehash.phash(pil_img2)
|
| 55 |
+
|
| 56 |
+
ssim_scores.append(ssim_val)
|
| 57 |
+
phash_distances.append(phash_dist)
|
| 58 |
+
|
| 59 |
+
return frames, fps, ssim_scores, phash_distances
|
| 60 |
+
|
| 61 |
+
def analisar_cor_iluminacao(frames):
|
| 62 |
+
lum_corr_scores, color_corr_scores = [], []
|
| 63 |
+
for i in range(len(frames) - 1):
|
| 64 |
+
frame1, frame2 = frames[i], frames[i+1]
|
| 65 |
+
gray1, gray2 = cv2.cvtColor(frame1, cv2.COLOR_RGB2GRAY), cv2.cvtColor(frame2, cv2.COLOR_RGB2GRAY)
|
| 66 |
+
hist1_lum, hist2_lum = cv2.calcHist([gray1], [0], None, [256], [0,256]), cv2.calcHist([gray2], [0], None, [256], [0,256])
|
| 67 |
+
lum_corr = cv2.compareHist(hist1_lum, hist2_lum, cv2.HISTCMP_CORREL)
|
| 68 |
+
lum_corr_scores.append(lum_corr)
|
| 69 |
+
|
| 70 |
+
corrs = []
|
| 71 |
+
for chan in range(3):
|
| 72 |
+
hist1, hist2 = cv2.calcHist([frame1],[chan],None,[256],[0,256]), cv2.calcHist([frame2],[chan],None,[256],[0,256])
|
| 73 |
+
corrs.append(cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL))
|
| 74 |
+
color_corr_scores.append(np.mean(corrs))
|
| 75 |
+
|
| 76 |
+
return lum_corr_scores, color_corr_scores
|
| 77 |
+
|
| 78 |
+
def analisar_anomalias_movimento(frames):
|
| 79 |
+
magnitude_scores, orientation_variance_scores = [], []
|
| 80 |
+
prev_gray = cv2.cvtColor(frames[0], cv2.COLOR_RGB2GRAY)
|
| 81 |
+
for i in range(1, len(frames)):
|
| 82 |
+
current_gray = cv2.cvtColor(frames[i], cv2.COLOR_RGB2GRAY)
|
| 83 |
+
flow = cv2.calcOpticalFlowFarneback(prev_gray, current_gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)
|
| 84 |
+
magnitude, angle = cv2.cartToPolar(flow[...,0], flow[...,1])
|
| 85 |
+
magnitude_scores.append(np.mean(magnitude))
|
| 86 |
+
orientation_variance_scores.append(np.var(angle))
|
| 87 |
+
prev_gray = current_gray
|
| 88 |
+
return magnitude_scores, orientation_variance_scores
|
| 89 |
+
|
| 90 |
+
def analisar_estabilidade_foco(frames):
|
| 91 |
+
ssim_foco_scores, jitter_foco_scores = [], []
|
| 92 |
+
last_roi_center = None
|
| 93 |
+
for i in range(len(frames) - 1):
|
| 94 |
+
frame1, frame2 = frames[i], frames[i+1]
|
| 95 |
+
try:
|
| 96 |
+
_, saliencyMap1 = saliency_detector.computeSaliency(frame1)
|
| 97 |
+
_, saliencyMap2 = saliency_detector.computeSaliency(frame2)
|
| 98 |
+
saliencyMap1_8bit, saliencyMap2_8bit = (saliencyMap1 * 255).astype("uint8"), (saliencyMap2 * 255).astype("uint8")
|
| 99 |
+
_, thresh1, _, thresh2 = cv2.threshold(saliencyMap1_8bit, 0, 255, cv2.THRESH_OTSU), cv2.threshold(saliencyMap2_8bit, 0, 255, cv2.THRESH_OTSU)
|
| 100 |
+
contours1, _ = cv2.findContours(thresh1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 101 |
+
contours2, _ = cv2.findContours(thresh2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 102 |
+
|
| 103 |
+
if contours1 and contours2:
|
| 104 |
+
x1, y1, w1, h1 = cv2.boundingRect(max(contours1, key=cv2.contourArea))
|
| 105 |
+
x2, y2, w2, h2 = cv2.boundingRect(max(contours2, key=cv2.contourArea))
|
| 106 |
+
roi1, roi2 = frame1[y1:y1+h1, x1:x1+w1], frame2[y2:y2+h2, x2:x2+w2]
|
| 107 |
+
roi1_gray, roi2_gray = cv2.cvtColor(roi1, cv2.COLOR_RGB2GRAY), cv2.cvtColor(roi2, cv2.COLOR_RGB2GRAY)
|
| 108 |
+
roi2_gray_resized = cv2.resize(roi2_gray, (roi1_gray.shape[1], roi1_gray.shape[0]))
|
| 109 |
+
|
| 110 |
+
ssim_foco, _ = ssim(roi1_gray, roi2_gray_resized, full=True, data_range=255) if min(roi1_gray.shape) > 7 else (0, None)
|
| 111 |
+
ssim_foco_scores.append(ssim_foco)
|
| 112 |
+
|
| 113 |
+
center = (x1 + w1/2, y1 + h1/2)
|
| 114 |
+
jitter_foco_scores.append(np.linalg.norm(np.array(center) - np.array(last_roi_center)) if last_roi_center else 0)
|
| 115 |
+
last_roi_center = center
|
| 116 |
+
else:
|
| 117 |
+
ssim_foco_scores.append(0); jitter_foco_scores.append(0)
|
| 118 |
+
except:
|
| 119 |
+
ssim_foco_scores.append(0); jitter_foco_scores.append(0)
|
| 120 |
+
return ssim_foco_scores, jitter_foco_scores
|
| 121 |
+
|
| 122 |
+
def executar_teste_semantico(phash_distances, descriptions_text):
|
| 123 |
+
# (Função como definida anteriormente)
|
| 124 |
+
return None, "Função ainda não implementada completamente no template"
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# --- FUNÇÕES DE PLOTAGEM ---
|
| 128 |
+
# (Todas as suas funções `gerar_grafico_...` devem estar aqui)
|
| 129 |
+
def gerar_grafico_fidelidade(ssim, phash, num_frames, fps):
|
| 130 |
+
path = "fidelidade.png"
|
| 131 |
+
# ... lógica de plotagem ...
|
| 132 |
+
plt.figure(); plt.plot(ssim); plt.savefig(path); plt.close()
|
| 133 |
+
return path
|
| 134 |
+
# ... e assim por diante para todas as outras funções de plotagem ...
|
| 135 |
+
|
| 136 |
|
| 137 |
# --- FUNÇÃO DE CALLBACK PRINCIPAL ---
|
| 138 |
+
def run_full_analysis(video_path, descriptions_text, progress=gr.Progress):
|
| 139 |
+
if video_path is None: raise gr.Error("Faça o upload de um vídeo.")
|
| 140 |
|
|
|
|
| 141 |
progress(0, desc="Analisando fidelidade...")
|
| 142 |
+
frames, fps, ssim_scores, phash_distances = analisar_fidelidade(video_path)
|
| 143 |
|
| 144 |
+
progress(0.2, desc="Gerando gráfico de fidelidade...")
|
| 145 |
fidelidade_plot_path = gerar_grafico_fidelidade(ssim_scores, phash_distances, len(frames), fps)
|
|
|
|
|
|
|
| 146 |
|
| 147 |
+
progress(0.3, desc="Analisando cor e iluminação...")
|
| 148 |
+
lum_scores, color_scores = analisar_cor_iluminacao(frames)
|
| 149 |
+
cor_plot_path = "cor.png" # Placeholder para a função de plotagem
|
| 150 |
+
|
| 151 |
+
progress(0.4, desc="Analisando glitches de movimento...")
|
| 152 |
+
mag_scores, var_scores = analisar_anomalias_movimento(frames)
|
| 153 |
+
anomalias_plot_path = "anomalias.png" # Placeholder
|
| 154 |
|
| 155 |
+
foco_plot_path = None
|
| 156 |
if SALIENCY_AVAILABLE:
|
| 157 |
progress(0.6, desc="Analisando foco móvel...")
|
| 158 |
+
ssim_foco, jitter_foco = analisar_estabilidade_foco(frames)
|
| 159 |
+
foco_plot_path = "foco.png" # Placeholder
|
| 160 |
|
| 161 |
+
semantico_path = None
|
| 162 |
if CLIP_AVAILABLE and descriptions_text.strip():
|
| 163 |
progress(0.8, desc="Executando teste semântico...")
|
| 164 |
semantico_path, error_msg = executar_teste_semantico(phash_distances, descriptions_text)
|
|
|
|
| 169 |
# --- INTERFACE GRADIO ---
|
| 170 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 171 |
gr.Markdown("# Suíte de Validação Completa para Geração de Vídeo (ADUC-SDR)")
|
|
|
|
| 172 |
with gr.Row():
|
| 173 |
with gr.Column(scale=1):
|
| 174 |
video_input = gr.Video(label="1. Upload do vídeo")
|
| 175 |
descriptions_input = gr.Textbox(lines=5, label="2. Descrições (Opcional)", placeholder="Uma descrição por cena...")
|
| 176 |
analyze_button = gr.Button("3. Executar Análise Completa", variant="primary")
|
|
|
|
| 177 |
with gr.Tabs():
|
| 178 |
with gr.TabItem("1. Fidelidade e Coerência"):
|
| 179 |
plot_fidelidade = gr.Image(label="Gráfico de Análise de Fidelidade (SSIM e pHash)")
|
|
|
|
| 180 |
with gr.TabItem("2. Cor e Iluminação"):
|
| 181 |
plot_cor = gr.Image(label="Gráfico de Análise de Cor e Luminância")
|
|
|
|
| 182 |
with gr.TabItem("3. Foco (Vídeo Móvel)"):
|
| 183 |
plot_foco = gr.Image(label="Gráfico de Análise de Foco e Jitter")
|
|
|
|
| 184 |
with gr.TabItem("4. Glitches de Movimento"):
|
| 185 |
plot_anomalias = gr.Image(label="Gráfico do Detector de Anomalias de Movimento")
|
|
|
|
| 186 |
with gr.TabItem("5. Inteligência Adaptativa"):
|
| 187 |
plot_semantico = gr.Image(label="Gráfico de Estresse Semântico")
|
| 188 |
|
|
|
|
|
|
|
| 189 |
analyze_button.click(
|
| 190 |
fn=run_full_analysis,
|
| 191 |
inputs=[video_input, descriptions_input],
|
|
|
|
| 193 |
)
|
| 194 |
|
| 195 |
if __name__ == "__main__":
|
| 196 |
+
demo.queue().launch()
|