Spaces:
Sleeping
Sleeping
JaphetHernandez
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,105 +1,67 @@
|
|
1 |
-
|
2 |
import streamlit as st
|
|
|
|
|
3 |
from huggingface_hub import login
|
4 |
-
import pandas as pd
|
5 |
-
from threading import Thread
|
6 |
|
7 |
-
# Token
|
8 |
huggingface_token = st.secrets["HUGGINGFACEHUB_API_TOKEN"]
|
9 |
login(huggingface_token)
|
10 |
|
11 |
-
# Cargar el
|
12 |
-
model_id = "meta-llama/Llama-3.
|
13 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
14 |
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
|
15 |
-
tokenizer.pad_token = tokenizer.eos_token
|
16 |
-
|
17 |
-
MAX_INPUT_TOKEN_LENGTH = 10000
|
18 |
|
19 |
-
|
20 |
-
|
|
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
st.warning(f"Se recort贸 la entrada porque excedi贸 el l铆mite de {MAX_INPUT_TOKEN_LENGTH} tokens.")
|
25 |
|
26 |
-
|
27 |
-
|
28 |
-
input_ids=input_ids,
|
29 |
-
streamer=streamer,
|
30 |
-
max_new_tokens=max_new_tokens,
|
31 |
-
do_sample=True,
|
32 |
-
top_k=20,
|
33 |
-
top_p=0.9,
|
34 |
-
temperature=temperature,
|
35 |
-
num_return_sequences=3,
|
36 |
-
eos_token_id=[tokenizer.eos_token_id]
|
37 |
-
)
|
38 |
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
t.join() # Asegura que la generaci贸n haya terminado
|
43 |
-
|
44 |
-
outputs = []
|
45 |
-
for text in streamer:
|
46 |
-
outputs.append(text)
|
47 |
-
if not outputs:
|
48 |
-
raise ValueError("No se gener贸 ninguna respuesta.")
|
49 |
-
|
50 |
-
response = "".join(outputs).strip().split("\n")[0]
|
51 |
-
return response
|
52 |
-
except Exception as e:
|
53 |
-
st.error(f"Error durante la generaci贸n: {e}")
|
54 |
-
return "Error en la generaci贸n de texto."
|
55 |
-
|
56 |
-
def main():
|
57 |
-
st.title("Chat con Meta Llama 3.2 1B")
|
58 |
-
|
59 |
-
uploaded_file = st.file_uploader("Por favor, sube un archivo CSV para iniciar:", type=["csv"])
|
60 |
|
61 |
-
if
|
62 |
-
df = pd.read_csv(uploaded_file)
|
63 |
query = 'aspiring human resources specialist'
|
64 |
-
|
65 |
-
if 'job_title' in df.columns:
|
66 |
-
job_titles = df['job_title']
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
f"Result: {value}"
|
80 |
-
)
|
81 |
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
st.write(query)
|
86 |
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
|
95 |
-
|
96 |
-
|
97 |
-
if st.button("Iniciar nueva conversaci贸n"):
|
98 |
-
st.experimental_rerun()
|
99 |
-
elif st.button("Terminar"):
|
100 |
-
st.stop()
|
101 |
-
else:
|
102 |
-
st.error("La columna 'job_title' no se encuentra en el archivo CSV.")
|
103 |
|
104 |
-
|
105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
import streamlit as st
|
3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
4 |
+
from langchain.llms import HuggingFacePipeline
|
5 |
from huggingface_hub import login
|
|
|
|
|
6 |
|
7 |
+
# Token de Hugging Face (Secreto)
|
8 |
huggingface_token = st.secrets["HUGGINGFACEHUB_API_TOKEN"]
|
9 |
login(huggingface_token)
|
10 |
|
11 |
+
# Cargar el modelo Llama 3.1 y el tokenizador
|
12 |
+
model_id = "meta-llama/Llama-3.1-1B"
|
13 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
14 |
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
|
|
|
|
|
|
|
15 |
|
16 |
+
# Crear pipeline de generaci贸n de texto
|
17 |
+
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_length=1024)
|
18 |
+
llm_pipeline = HuggingFacePipeline(pipeline=pipe)
|
19 |
|
20 |
+
# Interfaz de Streamlit
|
21 |
+
st.title("Cosine Similarity with Llama 3.1")
|
|
|
22 |
|
23 |
+
# Subir archivo CSV
|
24 |
+
uploaded_file = st.file_uploader("Sube un archivo CSV con la columna 'job_title':", type=["csv"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
+
if uploaded_file is not None:
|
27 |
+
# Cargar el CSV en un DataFrame
|
28 |
+
df = pd.read_csv(uploaded_file)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
+
if 'job_title' in df.columns:
|
|
|
31 |
query = 'aspiring human resources specialist'
|
32 |
+
job_titles = df['job_title'].tolist()
|
|
|
|
|
33 |
|
34 |
+
# Definir el prompt para el LLM
|
35 |
+
prompt = (
|
36 |
+
f"You are given a query and a list of job titles. Your task is to calculate the cosine similarity "
|
37 |
+
f"between the query and each job title. The query is: '{query}'. For each job title, provide the similarity "
|
38 |
+
f"score as a new column in the dataframe, called 'Score'. Return the dataframe with job titles and scores.\n"
|
39 |
+
f"Job Titles: {job_titles}\n"
|
40 |
+
f"Output format:\n"
|
41 |
+
f"1. Job Title: [Job Title], Score: [Cosine Similarity Score]\n"
|
42 |
+
f"2. Job Title: [Job Title], Score: [Cosine Similarity Score]\n"
|
43 |
+
f"..."
|
44 |
+
)
|
|
|
|
|
45 |
|
46 |
+
# Mostrar el prompt inicial
|
47 |
+
st.write("Prompt enviado al LLM:")
|
48 |
+
st.write(prompt)
|
|
|
49 |
|
50 |
+
# Generar respuesta del LLM
|
51 |
+
if st.button("Generar puntajes de similitud"):
|
52 |
+
with st.spinner("Calculando similitudes con Llama 3.1..."):
|
53 |
+
try:
|
54 |
+
response = llm_pipeline(prompt)
|
55 |
+
st.write("Respuesta del modelo:")
|
56 |
+
st.write(response)
|
57 |
|
58 |
+
# Simular la asignaci贸n de puntajes en la columna 'Score' (ya que el modelo no ejecuta c谩lculos reales)
|
59 |
+
df['Score'] = [0.95] * len(df) # Este paso es solo ilustrativo
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
+
# Mostrar el dataframe actualizado
|
62 |
+
st.write("DataFrame con los puntajes de similitud:")
|
63 |
+
st.write(df)
|
64 |
+
except Exception as e:
|
65 |
+
st.error(f"Error durante la generaci贸n: {e}")
|
66 |
+
else:
|
67 |
+
st.error("La columna 'job_title' no se encuentra en el archivo CSV.")
|