manuelcozar55 commited on
Commit
f676a94
verified
1 Parent(s): a3092b0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -0
app.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ warnings.simplefilter(action='ignore', category=FutureWarning)
3
+
4
+ import PyPDF2
5
+ import gradio as gr
6
+ from langchain.prompts import PromptTemplate
7
+ from langchain.chains.summarize import load_summarize_chain
8
+ from huggingface_hub import login
9
+ from pathlib import Path
10
+ from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
11
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
12
+ import torch
13
+ import os
14
+
15
+ huggingface_token = os.getenv('HUGGINGFACE_TOKEN')
16
+
17
+ # Realizar el inicio de sesi贸n de Hugging Face solo si el token est谩 disponible
18
+ if huggingface_token:
19
+ login(token=huggingface_token)
20
+
21
+ # Configuraci贸n del modelo LLM
22
+ llm = HuggingFaceEndpoint(
23
+ repo_id="mistralai/Mistral-7B-Instruct-v0.3",
24
+ task="text-generation",
25
+ max_new_tokens=4096,
26
+ temperature=0.5,
27
+ do_sample=False,
28
+ )
29
+ llm_engine_hf = ChatHuggingFace(llm=llm)
30
+
31
+ # Configuraci贸n del modelo de clasificaci贸n
32
+ tokenizer = AutoTokenizer.from_pretrained("mrm8488/legal-longformer-base-8192-spanish")
33
+ model = AutoModelForSequenceClassification.from_pretrained("mrm8488/legal-longformer-base-8192-spanish")
34
+
35
+ id2label = {0: "multas", 1: "politicas_de_privacidad", 2: "contratos", 3: "denuncias", 4: "otros"}
36
+
37
+ def read_file(file):
38
+ file_path = file.name
39
+ if file_path.endswith('.pdf'):
40
+ return read_pdf(file_path)
41
+ else:
42
+ with open(file_path, 'r', encoding='utf-8') as f:
43
+ return f.read()
44
+
45
+ def read_pdf(file_path):
46
+ pdf_reader = PyPDF2.PdfReader(file_path)
47
+ text = ""
48
+ for page in range(len(pdf_reader.pages)):
49
+ text += pdf_reader.pages[page].extract_text()
50
+ return text
51
+
52
+ def summarize(text, summary_length):
53
+ if summary_length == 'Corto':
54
+ length_instruction = "El resumen debe tener un m谩ximo de 100 palabras."
55
+ elif summary_length == 'Medio':
56
+ length_instruction = "El resumen debe tener un m谩ximo de 500 palabras."
57
+ else:
58
+ length_instruction = "El resumen debe tener un m谩ximo de 1000 palabras."
59
+
60
+ template = f'''
61
+ Por favor, lea detenidamente el siguiente documento:
62
+ <document>
63
+ {{TEXT}}
64
+ </document>
65
+ Despu茅s de leer el documento, identifique los puntos clave y las ideas principales cubiertas en el texto. {length_instruction}
66
+ Su objetivo es ser exhaustivo en la captura del contenido central del documento, mientras que tambi茅n es conciso en la expresi贸n de cada punto del resumen. Omita los detalles menores y conc茅ntrese en los temas centrales y hechos importantes.
67
+ '''
68
+
69
+ prompt = PromptTemplate(
70
+ template=template,
71
+ input_variables=['TEXT']
72
+ )
73
+
74
+ formatted_prompt = prompt.format(TEXT=text)
75
+ output_summary = llm_engine_hf.invoke(formatted_prompt)
76
+
77
+ return output_summary.content
78
+
79
+ def classify_text(text):
80
+ inputs = tokenizer(text, return_tensors="pt", max_length=4096, truncation=True, padding="max_length")
81
+ model.eval()
82
+ with torch.no_grad():
83
+ outputs = model(**inputs)
84
+ logits = outputs.logits
85
+ predicted_class_id = logits.argmax(dim=-1).item()
86
+ predicted_label = id2label[predicted_class_id]
87
+ return f"Clasificaci贸n: {predicted_label}"
88
+
89
+ def translate(text, target_language):
90
+ template = '''
91
+ Por favor, traduzca el siguiente documento al {LANGUAGE}:
92
+ <document>
93
+ {TEXT}
94
+ </document>
95
+ Aseg煤rese de que la traducci贸n sea precisa y conserve el significado original del documento.
96
+ '''
97
+
98
+ prompt = PromptTemplate(
99
+ template=template,
100
+ input_variables=['TEXT', 'LANGUAGE']
101
+ )
102
+
103
+ formatted_prompt = prompt.format(TEXT=text, LANGUAGE=target_language)
104
+ translated_text = llm_engine_hf.invoke(formatted_prompt)
105
+
106
+ return translated_text.content
107
+
108
+ def process_file(file, action, target_language=None, summary_length=None):
109
+ text = read_file(file)
110
+ if action == "Resumen":
111
+ return summarize(text, summary_length)
112
+ elif action == "Clasificar":
113
+ return classify_text(text)
114
+ elif action == "Traducir":
115
+ return translate(text, target_language)
116
+ else:
117
+ return "Acci贸n no v谩lida"
118
+
119
+ # Crear la interfaz de Gradio
120
+ with gr.Blocks() as demo:
121
+ gr.Markdown("## LexAIcon Traducci贸n, Resumen y Clasificaci贸n")
122
+ gr.Image("icon.jpg", width=100)
123
+
124
+ with gr.Row():
125
+ with gr.Column():
126
+ file = gr.File(label="Subir un archivo")
127
+ action = gr.Radio(label="Seleccione una acci贸n", choices=["Resumen", "Clasificar", "Traducir"])
128
+ summary_length = gr.Radio(label="Seleccione la longitud del resumen", choices=["Corto", "Medio", "Largo"], visible=False)
129
+ target_language = gr.Dropdown(label="Seleccionar idioma de traducci贸n", choices=["en", "fr", "de"], visible=False)
130
+
131
+ with gr.Column():
132
+ output_text = gr.Textbox(label="Resultado", lines=60)
133
+
134
+ def update_ui(action):
135
+ if action == "Traducir":
136
+ return gr.update(visible=False), gr.update(visible=True)
137
+ elif action == "Resumen":
138
+ return gr.update(visible=True), gr.update(visible(False))
139
+ elif action == "Clasificar":
140
+ return gr.update(visible(False)), gr.update(visible=False)
141
+ else:
142
+ return gr.update(visible=False), gr.update(visible(False))
143
+
144
+ action.change(update_ui, inputs=action, outputs=[summary_length, target_language])
145
+
146
+ submit_button = gr.Button("Procesar")
147
+ submit_button.click(process_file, inputs=[file, action, target_language, summary_length], outputs=output_text)
148
+
149
+ # Ejecutar la aplicaci贸n Gradio
150
+ demo.launch(share=True)