Spaces:
Running
Running
JaphetHernandez
commited on
Commit
•
235f923
1
Parent(s):
2a1126f
Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import pandas as pd
|
2 |
import streamlit as st
|
3 |
from langchain.llms import HuggingFacePipeline
|
@@ -81,3 +207,4 @@ if uploaded_file is not None:
|
|
81 |
st.error(f"Error durante la generación: {e}")
|
82 |
else:
|
83 |
st.error("La columna 'job_title' no se encuentra en el archivo CSV.")
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import streamlit as st
|
3 |
+
from langchain_huggingface import HuggingFacePipeline # Nueva importación
|
4 |
+
from langchain_core.prompts import PromptTemplate
|
5 |
+
from langchain.chains import LLMChain
|
6 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
7 |
+
from huggingface_hub import login
|
8 |
+
import torch
|
9 |
+
import json
|
10 |
+
from datetime import datetime
|
11 |
+
|
12 |
+
# Autenticación con Fireworks en Hugging Face
|
13 |
+
huggingface_token = st.secrets["FIREWORKS"]
|
14 |
+
login(huggingface_token)
|
15 |
+
|
16 |
+
# Configurar modelo Fireworks desde Hugging Face
|
17 |
+
model_id = "fireworks-ai/firefunction-v2"
|
18 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
19 |
+
model = AutoModelForCausalLM.from_pretrained(
|
20 |
+
model_id,
|
21 |
+
device_map="auto",
|
22 |
+
torch_dtype=torch.float16
|
23 |
+
)
|
24 |
+
|
25 |
+
# Definir funciones específicas para Fireworks
|
26 |
+
function_spec = [
|
27 |
+
{
|
28 |
+
"name": "calculate_cosine_similarity",
|
29 |
+
"description": "Calculate the cosine similarity between two strings.",
|
30 |
+
"parameters": {
|
31 |
+
"type": "object",
|
32 |
+
"properties": {
|
33 |
+
"query": {
|
34 |
+
"type": "string",
|
35 |
+
"description": "The main query string for similarity calculation"
|
36 |
+
},
|
37 |
+
"job_title": {
|
38 |
+
"type": "string",
|
39 |
+
"description": "The job title to compare with the query"
|
40 |
+
}
|
41 |
+
},
|
42 |
+
"required": ["query", "job_title"]
|
43 |
+
}
|
44 |
+
}
|
45 |
+
]
|
46 |
+
functions = json.dumps(function_spec, indent=4)
|
47 |
+
|
48 |
+
# Crear pipeline para generación de texto con Fireworks
|
49 |
+
fireworks_pipeline = pipeline(
|
50 |
+
"text-generation",
|
51 |
+
model=model,
|
52 |
+
tokenizer=tokenizer,
|
53 |
+
max_new_tokens=128
|
54 |
+
)
|
55 |
+
|
56 |
+
# Adaptar el pipeline a LangChain
|
57 |
+
llm_pipeline = HuggingFacePipeline(pipeline=fireworks_pipeline)
|
58 |
+
|
59 |
+
# Interfaz de Streamlit
|
60 |
+
st.title("Cosine Similarity Calculation with Fireworks, LangChain, and Llama 3.1")
|
61 |
+
|
62 |
+
# Subir archivo CSV
|
63 |
+
uploaded_file = st.file_uploader("Sube un archivo CSV con la columna 'job_title':", type=["csv"])
|
64 |
+
|
65 |
+
if uploaded_file is not None:
|
66 |
+
# Cargar el CSV en un DataFrame
|
67 |
+
df = pd.read_csv(uploaded_file)
|
68 |
+
if 'job_title' in df.columns:
|
69 |
+
query = 'aspiring human resources specialist'
|
70 |
+
job_titles = df['job_title'].tolist()
|
71 |
+
|
72 |
+
# Definir el prompt para Fireworks
|
73 |
+
prompt_template = PromptTemplate(
|
74 |
+
template=(
|
75 |
+
"Calculate the cosine similarity between the query: '{query}' "
|
76 |
+
"and the list of job titles: {job_titles}. "
|
77 |
+
"Return the results as 'Job Title: [Job Title], Score: [Cosine Similarity Score]'."
|
78 |
+
),
|
79 |
+
input_variables=["query", "job_titles"]
|
80 |
+
)
|
81 |
+
|
82 |
+
# Crear el LLMChain para manejar la interacción con Fireworks
|
83 |
+
llm_chain = LLMChain(
|
84 |
+
llm=llm_pipeline,
|
85 |
+
prompt=prompt_template
|
86 |
+
)
|
87 |
+
|
88 |
+
# Ejecutar la generación con Fireworks y funciones
|
89 |
+
if st.button("Calcular Similitud de Coseno"):
|
90 |
+
with st.spinner("Calculando similitudes con Fireworks..."):
|
91 |
+
try:
|
92 |
+
# Preparar mensajes y funciones para Fireworks
|
93 |
+
messages = [
|
94 |
+
{'role': 'system', 'content': 'You are a helpful assistant with access to functions. Use them if required.'},
|
95 |
+
{'role': 'user', 'content': f'Calculate cosine similarity for query: {query} with job titles.'}
|
96 |
+
]
|
97 |
+
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
98 |
+
|
99 |
+
model_inputs = tokenizer.apply_chat_template(
|
100 |
+
messages,
|
101 |
+
functions=functions,
|
102 |
+
datetime=now,
|
103 |
+
return_tensors="pt"
|
104 |
+
).to(model.device)
|
105 |
+
|
106 |
+
# Generar resultados con Fireworks
|
107 |
+
generated_ids = model.generate(model_inputs, max_new_tokens=128)
|
108 |
+
decoded = tokenizer.batch_decode(generated_ids)
|
109 |
+
st.write("Respuesta del modelo:")
|
110 |
+
st.write(decoded[0])
|
111 |
+
|
112 |
+
# Simular la asignación de puntajes en la columna 'Score' (basado en la respuesta del modelo)
|
113 |
+
df['Score'] = [0.95] * len(df) # Simulación para la demostración
|
114 |
+
|
115 |
+
# Mostrar el dataframe actualizado
|
116 |
+
st.write("DataFrame con los puntajes de similitud:")
|
117 |
+
st.write(df)
|
118 |
+
except Exception as e:
|
119 |
+
st.error(f"Error durante la generación: {e}")
|
120 |
+
else:
|
121 |
+
st.error("La columna 'job_title' no se encuentra en el archivo CSV.")
|
122 |
+
|
123 |
+
|
124 |
+
'''
|
125 |
+
|
126 |
+
|
127 |
import pandas as pd
|
128 |
import streamlit as st
|
129 |
from langchain.llms import HuggingFacePipeline
|
|
|
207 |
st.error(f"Error durante la generación: {e}")
|
208 |
else:
|
209 |
st.error("La columna 'job_title' no se encuentra en el archivo CSV.")
|
210 |
+
'''
|