JaphetHernandez commited on
Commit
f762e1b
verified
1 Parent(s): 275dee5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -86
app.py CHANGED
@@ -1,105 +1,67 @@
1
- from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
2
  import streamlit as st
 
 
3
  from huggingface_hub import login
4
- import pandas as pd
5
- from threading import Thread
6
 
7
- # Token Secret de Hugging Face
8
  huggingface_token = st.secrets["HUGGINGFACEHUB_API_TOKEN"]
9
  login(huggingface_token)
10
 
11
- # Cargar el tokenizador y el modelo
12
- model_id = "meta-llama/Llama-3.2-1B"
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
- def generate_response(input_text, temperature=0.7, max_new_tokens=20):
20
- input_ids = tokenizer.encode(input_text, return_tensors='pt').to(model.device)
 
21
 
22
- if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
23
- input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
24
- st.warning(f"Se recort贸 la entrada porque excedi贸 el l铆mite de {MAX_INPUT_TOKEN_LENGTH} tokens.")
25
 
26
- streamer = TextIteratorStreamer(tokenizer, timeout=120.0, skip_prompt=True, skip_special_tokens=True)
27
- generate_kwargs = dict(
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
- try:
40
- t = Thread(target=model.generate, kwargs=generate_kwargs)
41
- t.start()
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 uploaded_file is not None:
62
- df = pd.read_csv(uploaded_file)
63
  query = 'aspiring human resources specialist'
64
- value = 0.00
65
- if 'job_title' in df.columns:
66
- job_titles = df['job_title']
67
 
68
- # Definir el prompt con in-context learning
69
- initial_prompt = (
70
- "Step 1: Extract the first record from the dataframe df.\n"
71
- f" {df.iloc[0]['job_title']}\n"
72
- #f"List: {job_titles}\n"
73
- #"First job title: \n"
74
- #"\n"
75
- "Step 2: Calculate the cosine similarity score between the job_title of the extracted record {df.iloc[0]['job_title']} and the given {query} and assign it to {value}.\n"
76
- f"Query: '{query}'\n"
77
- "Cosine similarity score: \n"
78
- "Step 3: Print the value of the calculated cosine similarity"
79
- f"Result: {value}"
80
- )
81
 
82
-
83
- st.write("Prompt inicial con In-context Learning:\n")
84
- st.write(initial_prompt)
85
- st.write(query)
86
 
87
- if st.button("Generar respuesta"):
88
- with st.spinner("Generando respuesta..."):
89
- response = generate_response(initial_prompt, temperature=0.5)
90
- if response:
91
- st.write(f"Respuesta del modelo: {response}")
92
- else:
93
- st.warning("No se pudo generar una respuesta.")
94
 
95
- st.success("La conversaci贸n ha terminado.")
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
- if __name__ == "__main__":
105
- main()
 
 
 
 
 
 
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.")