vcasas commited on
Commit
87d2c80
·
verified ·
1 Parent(s): 9ef2fec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -49
app.py CHANGED
@@ -1,59 +1,89 @@
1
  import os
2
  import requests
3
- from llama_index.core import VectorStoreIndex, Settings, Document
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
- # 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
- # Crear índice desde un archivo PDF
19
- def create_index_from_pdf(pdf_path, model_name='nlpaueb/legal-bert-base-uncased'):
20
- pdf_reader = PDFReader()
21
- # Leer el contenido del PDF como documentos
22
- documents = pdf_reader.load_data(file=pdf_path)
23
-
24
- # Crear embeddings con un modelo más específico
25
- embed_model = HuggingFaceEmbedding(model_name=model_name)
26
- index = VectorStoreIndex.from_documents(
27
- documents,
28
- embed_model=embed_model
29
- )
30
- query_engine = index.as_query_engine(
31
- similarity_top_k=5, # Aumentar documentos relevantes
32
- response_mode="simple" # Generar respuestas completas
33
- )
34
- return query_engine
35
-
36
- # Función de búsqueda
37
- def search_pdf(query):
38
- response = query_engine.query(query)
39
- return response.response
40
-
41
- # Configurar parámetros
42
- pdf_url = 'https://www.boe.es/buscar/pdf/1995/BOE-A-1995-25444-consolidado.pdf'
43
- pdf_path = './BOE-A-1995-25444-consolidado.pdf'
44
-
45
- # Descargar y procesar el PDF
46
- if not os.path.exists(pdf_path):
47
- download_pdf(pdf_url, pdf_path)
48
-
49
- # Crear índice semántico
50
- query_engine = create_index_from_pdf(pdf_path)
51
-
52
- # Interfaz con Gradio
53
- gr.Interface(
54
- fn=search_pdf,
55
- inputs="text",
56
- outputs="text",
57
- title="Búsqueda en Código Penal PDF",
58
- description="Sube el Código Penal o pregunta directamente por información específica."
59
- ).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()