Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,106 +1,53 @@
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
-
import
|
| 4 |
-
from
|
| 5 |
-
from sentence_transformers import SentenceTransformer, util
|
| 6 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
# 1. Descargar el PDF
|
| 9 |
def download_pdf(url, destination):
|
| 10 |
-
"""Descarga un PDF desde una URL y lo guarda en la ruta especificada."""
|
| 11 |
os.makedirs(os.path.dirname(destination), exist_ok=True)
|
| 12 |
response = requests.get(url)
|
| 13 |
with open(destination, 'wb') as f:
|
| 14 |
f.write(response.content)
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
reader = PdfReader(pdf_path)
|
| 20 |
-
text = ""
|
| 21 |
-
for page in reader.pages:
|
| 22 |
-
text += page.extract_text()
|
| 23 |
-
|
| 24 |
-
# Usar regex para segmentar los artículos
|
| 25 |
-
article_pattern = r'(Artículo \d+\..*?)(?=Artículo \d+\.|$)'
|
| 26 |
-
matches = re.findall(article_pattern, text, re.DOTALL)
|
| 27 |
-
|
| 28 |
-
# Crear un diccionario de artículos
|
| 29 |
-
articles = {}
|
| 30 |
-
for match in matches:
|
| 31 |
-
lines = match.strip().split("\n")
|
| 32 |
-
title = lines[0].strip() # Ejemplo: "Artículo 138."
|
| 33 |
-
content = " ".join(line.strip() for line in lines[1:]).strip()
|
| 34 |
-
articles[title] = content
|
| 35 |
-
|
| 36 |
-
return articles
|
| 37 |
-
|
| 38 |
-
# 3. Crear embeddings para los artículos
|
| 39 |
-
def create_article_embeddings(articles, model_name="paraphrase-multilingual-mpnet-base-v2"):
|
| 40 |
-
"""Crea embeddings para los artículos utilizando SentenceTransformers."""
|
| 41 |
-
model = SentenceTransformer(model_name)
|
| 42 |
-
article_keys = list(articles.keys())
|
| 43 |
-
article_embeddings = model.encode(list(articles.values()), convert_to_tensor=True)
|
| 44 |
-
return article_keys, article_embeddings, model
|
| 45 |
-
|
| 46 |
-
# 4. Buscar el artículo relevante
|
| 47 |
-
def find_article(question, article_keys, article_embeddings, model, articles):
|
| 48 |
-
# Filtrar artículos relevantes usando palabras clave
|
| 49 |
-
keywords = question.lower().split() # Dividir pregunta en palabras clave
|
| 50 |
-
filtered_articles = {
|
| 51 |
-
key: value for key, value in articles.items()
|
| 52 |
-
if any(keyword in value.lower() for keyword in keywords)
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
-
if not filtered_articles:
|
| 56 |
-
# Si no hay artículos relevantes basados en palabras clave, usar todos
|
| 57 |
-
filtered_articles = articles
|
| 58 |
-
|
| 59 |
-
# Crear nuevos embeddings para los artículos filtrados
|
| 60 |
-
filtered_keys = list(filtered_articles.keys())
|
| 61 |
-
filtered_embeddings = model.encode(list(filtered_articles.values()), convert_to_tensor=True)
|
| 62 |
-
|
| 63 |
-
# Calcular similitud con la pregunta
|
| 64 |
-
question_embedding = model.encode(question, convert_to_tensor=True)
|
| 65 |
-
scores = util.pytorch_cos_sim(question_embedding, filtered_embeddings)
|
| 66 |
-
best_match_idx = scores.argmax()
|
| 67 |
-
best_article_key = filtered_keys[best_match_idx]
|
| 68 |
-
return f"{best_article_key}\n{filtered_articles[best_article_key]}"
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
# Flujo principal
|
| 72 |
-
def main():
|
| 73 |
-
# Configuración inicial
|
| 74 |
-
pdf_url = 'https://www.boe.es/buscar/pdf/1995/BOE-A-1995-25444-consolidado.pdf'
|
| 75 |
-
pdf_path = './BOE-A-1995-25444-consolidado.pdf'
|
| 76 |
-
|
| 77 |
-
# Descargar el PDF si no existe
|
| 78 |
-
if not os.path.exists(pdf_path):
|
| 79 |
-
print("Descargando el Código Penal...")
|
| 80 |
-
download_pdf(pdf_url, pdf_path)
|
| 81 |
-
|
| 82 |
-
# Extraer y procesar los artículos
|
| 83 |
-
print("Extrayendo artículos del Código Penal...")
|
| 84 |
-
articles = extract_articles_from_pdf(pdf_path)
|
| 85 |
-
|
| 86 |
-
# Crear embeddings para los artículos
|
| 87 |
-
print("Creando embeddings para los artículos...")
|
| 88 |
-
article_keys, article_embeddings, model = create_article_embeddings(articles)
|
| 89 |
-
|
| 90 |
-
# Función para responder preguntas
|
| 91 |
-
def search_law(query):
|
| 92 |
-
return find_article(query, article_keys, article_embeddings, model, articles)
|
| 93 |
-
|
| 94 |
-
# Iniciar la interfaz de Gradio
|
| 95 |
-
print("Lanzando la aplicación...")
|
| 96 |
-
gr.Interface(
|
| 97 |
-
fn=search_law,
|
| 98 |
-
inputs="text",
|
| 99 |
-
outputs="text",
|
| 100 |
-
title="Búsqueda en el Código Penal Español",
|
| 101 |
-
description="Realiza preguntas sobre delitos y penas en el Código Penal Español."
|
| 102 |
-
).launch()
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
+
from llama_index.core import VectorStoreIndex, Settings
|
| 4 |
+
from llama_index.readers.file import PDFReader
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
+
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
| 7 |
+
|
| 8 |
+
# Disable the default LLM
|
| 9 |
+
Settings.llm = None
|
| 10 |
|
|
|
|
| 11 |
def download_pdf(url, destination):
|
|
|
|
| 12 |
os.makedirs(os.path.dirname(destination), exist_ok=True)
|
| 13 |
response = requests.get(url)
|
| 14 |
with open(destination, 'wb') as f:
|
| 15 |
f.write(response.content)
|
| 16 |
|
| 17 |
+
def create_index_from_pdf(pdf_path):
|
| 18 |
+
pdf_reader = PDFReader()
|
| 19 |
+
documents = pdf_reader.load_data(file=pdf_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
embed_model = HuggingFaceEmbedding(model_name='BAAI/bge-large-es')
|
| 22 |
+
|
| 23 |
+
index = VectorStoreIndex.from_documents(
|
| 24 |
+
documents,
|
| 25 |
+
embed_model=embed_model
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
query_engine = index.as_query_engine(
|
| 29 |
+
similarity_top_k=3, # Increased to find more relevant context
|
| 30 |
+
response_mode="compact"
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
return query_engine
|
| 34 |
+
|
| 35 |
+
pdf_url = 'https://www.boe.es/buscar/pdf/1995/BOE-A-1995-25444-consolidado.pdf'
|
| 36 |
+
pdf_path = './BOE-A-1995-25444-consolidado.pdf'
|
| 37 |
+
|
| 38 |
+
download_pdf(pdf_url, pdf_path)
|
| 39 |
+
query_engine = create_index_from_pdf(pdf_path)
|
| 40 |
+
|
| 41 |
+
def search_pdf(query):
|
| 42 |
+
# Modificar la consulta para buscar específicamente penas
|
| 43 |
+
modified_query = f"Pena para el delito de {query}"
|
| 44 |
+
response = query_engine.query(modified_query)
|
| 45 |
+
return response.response
|
| 46 |
+
|
| 47 |
+
gr.Interface(
|
| 48 |
+
fn=search_pdf,
|
| 49 |
+
inputs="text",
|
| 50 |
+
outputs="text",
|
| 51 |
+
title="Buscador de Penas en Código Penal",
|
| 52 |
+
description="Introduce un tipo de delito para encontrar su pena correspondiente"
|
| 53 |
+
).launch()
|