Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,15 +1,14 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import html2text
|
| 3 |
from bs4 import BeautifulSoup
|
| 4 |
-
import logging
|
| 5 |
|
| 6 |
-
# Configurar logging básico para ver qual contêiner foi escolhido
|
| 7 |
logging.basicConfig(level=logging.INFO)
|
| 8 |
|
| 9 |
-
def
|
| 10 |
"""
|
| 11 |
-
Tenta extrair o conteúdo principal
|
| 12 |
-
|
| 13 |
|
| 14 |
:param html_bruto: String contendo o código HTML original.
|
| 15 |
:return: String contendo o HTML limpo e focado no conteúdo principal.
|
|
@@ -21,81 +20,105 @@ def extrair_limpar_html(html_bruto):
|
|
| 21 |
target_element = None
|
| 22 |
|
| 23 |
# --- 1. Tentar Extrair o Conteúdo Principal ---
|
| 24 |
-
# Lista de seletores CSS em ordem de preferência
|
| 25 |
-
# (Mais específicos primeiro)
|
| 26 |
main_content_selectors = [
|
|
|
|
| 27 |
'main', # <main> tag
|
| 28 |
-
'article', # <article> tag (primeiro encontrado)
|
| 29 |
'[role="main"]', # role="main" attribute
|
| 30 |
-
'#content', # ID #content
|
| 31 |
-
'#main', # ID #main
|
| 32 |
-
'.main-content', # Classe .main-content
|
| 33 |
'.post', # Classe .post
|
| 34 |
-
'.entry-content', # Classe .entry-content
|
| 35 |
-
'.post-
|
|
|
|
| 36 |
'.article-body', # Classe .article-body
|
|
|
|
|
|
|
| 37 |
'#bodyContent', # ID específico da Wikipedia
|
| 38 |
-
# Adicione outros seletores comuns se necessário
|
| 39 |
]
|
| 40 |
|
| 41 |
for selector in main_content_selectors:
|
| 42 |
-
# select_one retorna o primeiro elemento que corresponde ao seletor
|
| 43 |
potential_match = soup.select_one(selector)
|
| 44 |
if potential_match:
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
# Fallback: Se nenhum seletor específico funcionou, usar o <body>
|
| 50 |
if not target_element:
|
| 51 |
if soup.body:
|
| 52 |
target_element = soup.body
|
| 53 |
logging.info("Nenhum contêiner principal específico encontrado. Usando <body> como fallback.")
|
| 54 |
else:
|
| 55 |
-
# Caso extremo: HTML sem body, usa o soup inteiro
|
| 56 |
target_element = soup
|
| 57 |
logging.warning("Nenhum contêiner principal ou <body> encontrado. Processando todo o input.")
|
| 58 |
|
| 59 |
-
# Se target_element for None (caso extremo), retorna vazio
|
| 60 |
if not target_element:
|
| 61 |
return ""
|
| 62 |
|
| 63 |
-
# --- 2.
|
| 64 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
for tag in target_element.find_all(tags_para_remover):
|
| 69 |
tag.decompose()
|
| 70 |
|
| 71 |
-
# Tags permitidas e atributos permitidos (ajuste conforme necessário)
|
| 72 |
tags_permitidas = {
|
| 73 |
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'br', 'a', 'strong', 'b',
|
| 74 |
'em', 'i', 'u', 's', 'strike', 'del', 'ul', 'ol', 'li', 'img',
|
| 75 |
-
'table', 'thead', 'tbody', 'tr', 'th', 'td', 'blockquote', 'pre', 'code'
|
| 76 |
-
|
| 77 |
}
|
| 78 |
atributos_permitidos = {
|
| 79 |
'a': ['href', 'title'],
|
| 80 |
'img': ['src', 'alt', 'title', 'width', 'height'],
|
| 81 |
-
|
| 82 |
-
|
| 83 |
}
|
| 84 |
|
| 85 |
-
# Iterar por todas as tags DENTRO do target_element
|
| 86 |
-
# Usar list() para poder modificar a estrutura durante a iteração
|
| 87 |
for tag in list(target_element.find_all(True)):
|
| 88 |
-
|
| 89 |
-
if not tag.parent:
|
| 90 |
-
continue
|
| 91 |
-
|
| 92 |
if tag.name not in tags_permitidas:
|
| 93 |
-
# Se a tag não é permitida, remove a tag mas mantém o conteúdo (unwrap)
|
| 94 |
-
# Evitar erro se tag já foi removida
|
| 95 |
tag.unwrap()
|
| 96 |
else:
|
| 97 |
-
|
| 98 |
-
atributos_para_manter = atributos_permitidos.get(tag.name, []) # + atributos_permitidos.get('*', []) # Removido '*'
|
| 99 |
attrs_mantidos = {}
|
| 100 |
for attr, value in tag.attrs.items():
|
| 101 |
if attr in atributos_para_manter:
|
|
@@ -103,54 +126,70 @@ def extrair_limpar_html(html_bruto):
|
|
| 103 |
tag.attrs = attrs_mantidos
|
| 104 |
|
| 105 |
# Retorna o HTML limpo e focado como string
|
|
|
|
| 106 |
return str(target_element)
|
| 107 |
|
| 108 |
-
|
| 109 |
-
def
|
| 110 |
"""
|
| 111 |
-
Extrai
|
| 112 |
"""
|
| 113 |
if not html_input:
|
| 114 |
return "Por favor, insira algum código HTML."
|
| 115 |
|
| 116 |
try:
|
| 117 |
-
# 1. Extrai
|
| 118 |
-
|
| 119 |
|
| 120 |
-
if not
|
| 121 |
-
return "HTML resultante após extração e limpeza está vazio ou contém
|
| 122 |
|
| 123 |
-
# 2. Converte o HTML
|
| 124 |
converter = html2text.HTML2Text()
|
| 125 |
converter.ignore_links = False
|
| 126 |
converter.ignore_images = False
|
| 127 |
-
converter.body_width = 0
|
| 128 |
-
#
|
| 129 |
-
#
|
| 130 |
-
# converter.
|
| 131 |
-
# converter.
|
| 132 |
|
| 133 |
-
markdown_output = converter.handle(
|
| 134 |
|
| 135 |
-
#
|
|
|
|
| 136 |
linhas = markdown_output.splitlines()
|
| 137 |
-
linhas_filtradas = [
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
except Exception as e:
|
| 143 |
-
# Logar o erro completo pode ser útil para depuração no servidor
|
| 144 |
logging.error(f"Erro durante o processo: {e}", exc_info=True)
|
| 145 |
-
return f"Ocorreu um erro durante o processo: {str(e)}. Verifique os logs para
|
|
|
|
| 146 |
|
| 147 |
# --- Cria a interface Gradio ---
|
| 148 |
iface = gr.Interface(
|
| 149 |
-
fn=
|
| 150 |
inputs=gr.Textbox(lines=20, label="Insira o HTML bruto aqui", placeholder="Cole o código-fonte HTML completo da página..."),
|
| 151 |
-
outputs=gr.Textbox(lines=20, label="Markdown Resultante (Conteúdo Principal)"),
|
| 152 |
-
title="Conversor HTML para Markdown (Foco no Conteúdo Principal)",
|
| 153 |
-
description="Cole o HTML completo. O script tentará identificar o conteúdo principal
|
| 154 |
allow_flagging='never'
|
| 155 |
)
|
| 156 |
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import html2text
|
| 3 |
from bs4 import BeautifulSoup
|
| 4 |
+
import logging
|
| 5 |
|
|
|
|
| 6 |
logging.basicConfig(level=logging.INFO)
|
| 7 |
|
| 8 |
+
def extrair_limpar_html_v2(html_bruto):
|
| 9 |
"""
|
| 10 |
+
Tenta extrair o conteúdo principal, remove seções finais comuns
|
| 11 |
+
(comentários, posts relacionados), limpa tags/atributos e retorna o HTML.
|
| 12 |
|
| 13 |
:param html_bruto: String contendo o código HTML original.
|
| 14 |
:return: String contendo o HTML limpo e focado no conteúdo principal.
|
|
|
|
| 20 |
target_element = None
|
| 21 |
|
| 22 |
# --- 1. Tentar Extrair o Conteúdo Principal ---
|
|
|
|
|
|
|
| 23 |
main_content_selectors = [
|
| 24 |
+
'article', # <article> tag (mais comum para posts individuais)
|
| 25 |
'main', # <main> tag
|
|
|
|
| 26 |
'[role="main"]', # role="main" attribute
|
|
|
|
|
|
|
|
|
|
| 27 |
'.post', # Classe .post
|
| 28 |
+
'.entry-content', # Classe .entry-content
|
| 29 |
+
'.post-content', # Classe .post-content
|
| 30 |
+
'.td-post-content', # Comum em alguns temas WP
|
| 31 |
'.article-body', # Classe .article-body
|
| 32 |
+
'#content', # ID #content
|
| 33 |
+
'#main', # ID #main
|
| 34 |
'#bodyContent', # ID específico da Wikipedia
|
|
|
|
| 35 |
]
|
| 36 |
|
| 37 |
for selector in main_content_selectors:
|
|
|
|
| 38 |
potential_match = soup.select_one(selector)
|
| 39 |
if potential_match:
|
| 40 |
+
# Verifica se o match não é apenas um container vazio ou muito pequeno
|
| 41 |
+
# (Pode precisar de ajuste)
|
| 42 |
+
if len(potential_match.get_text(strip=True)) > 100: # Heurística simples
|
| 43 |
+
target_element = potential_match
|
| 44 |
+
logging.info(f"Conteúdo principal identificado usando o seletor: '{selector}'")
|
| 45 |
+
break
|
| 46 |
|
|
|
|
| 47 |
if not target_element:
|
| 48 |
if soup.body:
|
| 49 |
target_element = soup.body
|
| 50 |
logging.info("Nenhum contêiner principal específico encontrado. Usando <body> como fallback.")
|
| 51 |
else:
|
|
|
|
| 52 |
target_element = soup
|
| 53 |
logging.warning("Nenhum contêiner principal ou <body> encontrado. Processando todo o input.")
|
| 54 |
|
|
|
|
| 55 |
if not target_element:
|
| 56 |
return ""
|
| 57 |
|
| 58 |
+
# --- 2. Remover Seções Finais Indesejadas DENTRO do target_element ---
|
| 59 |
+
# Lista de seletores para comentários, posts relacionados, formulários de resposta, etc.
|
| 60 |
+
end_content_selectors = [
|
| 61 |
+
'#comments', # ID comum para seção de comentários
|
| 62 |
+
'.comments-area', # Classe comum para seção de comentários
|
| 63 |
+
'#respond', # ID comum para formulário de resposta
|
| 64 |
+
'.comment-respond', # Classe comum para formulário de resposta
|
| 65 |
+
'.related-posts', # Classe comum para posts relacionados
|
| 66 |
+
'.jp-relatedposts', # Classe do Jetpack para posts relacionados
|
| 67 |
+
'.post-navigation', # Navegação entre posts
|
| 68 |
+
'.author-box', # Caixa de biografia do autor
|
| 69 |
+
'.share-buttons', # Botões de compartilhamento social
|
| 70 |
+
'#jp-post-flair', # Jetpack flair (pode incluir compartilhamento/relacionados)
|
| 71 |
+
'.yarpp-related', # Yet Another Related Posts Plugin
|
| 72 |
+
# Adicione seletores específicos do site/tema se necessário
|
| 73 |
+
# Exemplo baseado no HTML do usuário:
|
| 74 |
+
# Procurar por um h2 com texto "Comentários" ou "Mais posts" e remover seu container? (Mais frágil)
|
| 75 |
+
# Ou identificar os containers pelos IDs/classes se disponíveis.
|
| 76 |
+
# Se "Mais posts" estiver numa section ou div específica:
|
| 77 |
+
# '.mais-posts-section-class' # Substitua pelo seletor real
|
| 78 |
+
]
|
| 79 |
|
| 80 |
+
logging.info(f"Procurando por seções finais indesejadas dentro do elemento '{target_element.name}'...")
|
| 81 |
+
removed_count = 0
|
| 82 |
+
for selector in end_content_selectors:
|
| 83 |
+
# Encontra TODOS os elementos que correspondem dentro do target_element
|
| 84 |
+
elements_to_remove = target_element.select(selector)
|
| 85 |
+
for element in elements_to_remove:
|
| 86 |
+
# Verifica se o elemento ainda existe (pode ter sido removido como filho de outro)
|
| 87 |
+
if element.parent:
|
| 88 |
+
logging.info(f"Removendo seção final indesejada encontrada com seletor: '{selector}' (Tag: {element.name}, ID: {element.get('id', 'N/A')}, Classes: {element.get('class', [])})")
|
| 89 |
+
element.decompose() # Remove o elemento e todo o seu conteúdo
|
| 90 |
+
removed_count += 1
|
| 91 |
+
|
| 92 |
+
if removed_count > 0:
|
| 93 |
+
logging.info(f"Removidas {removed_count} seções finais indesejadas.")
|
| 94 |
+
else:
|
| 95 |
+
logging.info("Nenhuma seção final indesejada conhecida foi encontrada para remoção.")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# --- 3. Limpar o Restante do Elemento Selecionado ---
|
| 99 |
+
tags_para_remover = ['script', 'style', 'form', 'input', 'button', 'select', 'textarea', 'label', 'footer', 'header', 'nav', 'aside', 'iframe', 'noscript', 'meta', 'link']
|
| 100 |
for tag in target_element.find_all(tags_para_remover):
|
| 101 |
tag.decompose()
|
| 102 |
|
|
|
|
| 103 |
tags_permitidas = {
|
| 104 |
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'br', 'a', 'strong', 'b',
|
| 105 |
'em', 'i', 'u', 's', 'strike', 'del', 'ul', 'ol', 'li', 'img',
|
| 106 |
+
'table', 'thead', 'tbody', 'tr', 'th', 'td', 'blockquote', 'pre', 'code',
|
| 107 |
+
'figure', 'figcaption' # Adicionado figure/figcaption, comum para imagens com legendas
|
| 108 |
}
|
| 109 |
atributos_permitidos = {
|
| 110 |
'a': ['href', 'title'],
|
| 111 |
'img': ['src', 'alt', 'title', 'width', 'height'],
|
| 112 |
+
'th': ['colspan', 'rowspan'], # Útil para tabelas
|
| 113 |
+
'td': ['colspan', 'rowspan'],
|
| 114 |
}
|
| 115 |
|
|
|
|
|
|
|
| 116 |
for tag in list(target_element.find_all(True)):
|
| 117 |
+
if not tag.parent: continue
|
|
|
|
|
|
|
|
|
|
| 118 |
if tag.name not in tags_permitidas:
|
|
|
|
|
|
|
| 119 |
tag.unwrap()
|
| 120 |
else:
|
| 121 |
+
atributos_para_manter = atributos_permitidos.get(tag.name, [])
|
|
|
|
| 122 |
attrs_mantidos = {}
|
| 123 |
for attr, value in tag.attrs.items():
|
| 124 |
if attr in atributos_para_manter:
|
|
|
|
| 126 |
tag.attrs = attrs_mantidos
|
| 127 |
|
| 128 |
# Retorna o HTML limpo e focado como string
|
| 129 |
+
# Usar .prettify() pode ajudar na depuração, mas str() é mais direto
|
| 130 |
return str(target_element)
|
| 131 |
|
| 132 |
+
|
| 133 |
+
def html_para_markdown_final(html_input):
|
| 134 |
"""
|
| 135 |
+
Pipeline completo: Extrai conteúdo, limpa seções indesejadas e converte para Markdown.
|
| 136 |
"""
|
| 137 |
if not html_input:
|
| 138 |
return "Por favor, insira algum código HTML."
|
| 139 |
|
| 140 |
try:
|
| 141 |
+
# 1. Extrai, remove seções finais e limpa HTML
|
| 142 |
+
html_processado = extrair_limpar_html_v2(html_input)
|
| 143 |
|
| 144 |
+
if not html_processado or not BeautifulSoup(html_processado, 'html.parser').get_text(strip=True):
|
| 145 |
+
return "HTML resultante após extração e limpeza está vazio ou não contém texto."
|
| 146 |
|
| 147 |
+
# 2. Converte o HTML processado para Markdown
|
| 148 |
converter = html2text.HTML2Text()
|
| 149 |
converter.ignore_links = False
|
| 150 |
converter.ignore_images = False
|
| 151 |
+
converter.body_width = 0
|
| 152 |
+
converter.single_line_break = True # Trata <br> como uma única quebra de linha
|
| 153 |
+
# Outras opções podem ser úteis:
|
| 154 |
+
# converter.unicode_snob = True # Usa caracteres unicode para listas, etc.
|
| 155 |
+
# converter.escape_snob = True # Escapa caracteres especiais do Markdown
|
| 156 |
|
| 157 |
+
markdown_output = converter.handle(html_processado)
|
| 158 |
|
| 159 |
+
# 3. Pós-processamento do Markdown (opcional, mas útil)
|
| 160 |
+
# Remover linhas excessivas em branco
|
| 161 |
linhas = markdown_output.splitlines()
|
| 162 |
+
linhas_filtradas = []
|
| 163 |
+
espacos_consecutivos = 0
|
| 164 |
+
for linha in linhas:
|
| 165 |
+
linha_strip = linha.strip()
|
| 166 |
+
if not linha_strip:
|
| 167 |
+
espacos_consecutivos += 1
|
| 168 |
+
if espacos_consecutivos <= 2: # Permitir no máximo uma linha em branco entre blocos
|
| 169 |
+
linhas_filtradas.append(linha_strip)
|
| 170 |
+
else:
|
| 171 |
+
espacos_consecutivos = 0
|
| 172 |
+
linhas_filtradas.append(linha)
|
| 173 |
+
|
| 174 |
+
markdown_output = "\n".join(linhas_filtradas).strip()
|
| 175 |
|
| 176 |
+
# Remover possíveis artefatos de tabelas vazias ou listas vazias se necessário
|
| 177 |
+
# markdown_output = re.sub(r"\n\s*\n", "\n\n", markdown_output) # Exemplo de limpeza extra
|
| 178 |
+
|
| 179 |
+
return markdown_output
|
| 180 |
|
| 181 |
except Exception as e:
|
|
|
|
| 182 |
logging.error(f"Erro durante o processo: {e}", exc_info=True)
|
| 183 |
+
return f"Ocorreu um erro durante o processo: {str(e)}. Verifique os logs do Space para detalhes."
|
| 184 |
+
|
| 185 |
|
| 186 |
# --- Cria a interface Gradio ---
|
| 187 |
iface = gr.Interface(
|
| 188 |
+
fn=html_para_markdown_final, # Usando a função principal atualizada
|
| 189 |
inputs=gr.Textbox(lines=20, label="Insira o HTML bruto aqui", placeholder="Cole o código-fonte HTML completo da página..."),
|
| 190 |
+
outputs=gr.Textbox(lines=20, label="Markdown Resultante (Conteúdo Principal Limpo)"),
|
| 191 |
+
title="Conversor HTML para Markdown (Foco no Conteúdo Principal + Remoção de Comentários/Relacionados)",
|
| 192 |
+
description="Cole o HTML completo. O script tentará identificar o conteúdo principal, removerá seções comuns como comentários e posts relacionados no final do artigo, limpará tags/atributos irrelevantes e converterá para Markdown.",
|
| 193 |
allow_flagging='never'
|
| 194 |
)
|
| 195 |
|