Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,59 +1,89 @@
|
|
1 |
import os
|
2 |
import requests
|
3 |
-
|
4 |
-
from
|
|
|
5 |
import gradio as gr
|
6 |
-
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
7 |
|
8 |
-
#
|
9 |
-
Settings.llm = None
|
10 |
-
|
11 |
-
# Descargar y guardar PDF
|
12 |
def download_pdf(url, destination):
|
|
|
13 |
os.makedirs(os.path.dirname(destination), exist_ok=True)
|
14 |
response = requests.get(url)
|
15 |
with open(destination, 'wb') as f:
|
16 |
f.write(response.content)
|
17 |
|
18 |
-
#
|
19 |
-
def
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
import requests
|
3 |
+
import re
|
4 |
+
from PyPDF2 import PdfReader
|
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 |
+
# 2. Extraer los artículos del PDF
|
17 |
+
def extract_articles_from_pdf(pdf_path):
|
18 |
+
"""Extrae artículos del PDF basado en el formato del Código Penal."""
|
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 |
+
"""Busca el artículo más relevante para la pregunta utilizando embeddings."""
|
49 |
+
question_embedding = model.encode(question, convert_to_tensor=True)
|
50 |
+
scores = util.pytorch_cos_sim(question_embedding, article_embeddings)
|
51 |
+
best_match_idx = scores.argmax()
|
52 |
+
best_article_key = article_keys[best_match_idx]
|
53 |
+
return f"{best_article_key}\n{articles[best_article_key]}"
|
54 |
+
|
55 |
+
# Flujo principal
|
56 |
+
def main():
|
57 |
+
# Configuración inicial
|
58 |
+
pdf_url = 'https://www.boe.es/buscar/pdf/1995/BOE-A-1995-25444-consolidado.pdf'
|
59 |
+
pdf_path = './BOE-A-1995-25444-consolidado.pdf'
|
60 |
+
|
61 |
+
# Descargar el PDF si no existe
|
62 |
+
if not os.path.exists(pdf_path):
|
63 |
+
print("Descargando el Código Penal...")
|
64 |
+
download_pdf(pdf_url, pdf_path)
|
65 |
+
|
66 |
+
# Extraer y procesar los artículos
|
67 |
+
print("Extrayendo artículos del Código Penal...")
|
68 |
+
articles = extract_articles_from_pdf(pdf_path)
|
69 |
+
|
70 |
+
# Crear embeddings para los artículos
|
71 |
+
print("Creando embeddings para los artículos...")
|
72 |
+
article_keys, article_embeddings, model = create_article_embeddings(articles)
|
73 |
+
|
74 |
+
# Función para responder preguntas
|
75 |
+
def search_law(query):
|
76 |
+
return find_article(query, article_keys, article_embeddings, model, articles)
|
77 |
+
|
78 |
+
# Iniciar la interfaz de Gradio
|
79 |
+
print("Lanzando la aplicación...")
|
80 |
+
gr.Interface(
|
81 |
+
fn=search_law,
|
82 |
+
inputs="text",
|
83 |
+
outputs="text",
|
84 |
+
title="Búsqueda en el Código Penal Español",
|
85 |
+
description="Realiza preguntas sobre delitos y penas en el Código Penal Español."
|
86 |
+
).launch()
|
87 |
+
|
88 |
+
if __name__ == "__main__":
|
89 |
+
main()
|