Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,8 +1,8 @@
|
|
1 |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
2 |
-
from accelerate import init_empty_weights, load_checkpoint_and_dispatch, dispatch_model, infer_auto_device_map
|
3 |
import streamlit as st
|
4 |
from huggingface_hub import login
|
5 |
import pandas as pd
|
|
|
6 |
|
7 |
# Token Secret de Hugging Face
|
8 |
huggingface_token = st.secrets["HUGGINGFACEHUB_API_TOKEN"]
|
@@ -11,23 +11,13 @@ login(huggingface_token)
|
|
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
|
15 |
tokenizer.pad_token = tokenizer.eos_token
|
16 |
|
17 |
MAX_INPUT_TOKEN_LENGTH = 10000
|
18 |
|
19 |
-
# Cargar el modelo con disk_offload
|
20 |
-
with init_empty_weights():
|
21 |
-
model = AutoModelForCausalLM.from_config(model_id)
|
22 |
-
|
23 |
-
device_map = infer_auto_device_map(model, max_memory={"disk": "2GiB"}, no_split_module_classes=["LlamaDecoderLayer"])
|
24 |
-
model = load_checkpoint_and_dispatch(model, model_id, device_map=device_map, offload_folder="offload_dir")
|
25 |
-
|
26 |
-
MAX_INPUT_TOKEN_LENGTH = 10000
|
27 |
-
|
28 |
-
|
29 |
def generate_response(input_text, temperature=0.7, max_new_tokens=20):
|
30 |
-
input_ids = tokenizer.encode(input_text, return_tensors='pt').to(
|
31 |
|
32 |
if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
|
33 |
input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
|
@@ -43,14 +33,22 @@ def generate_response(input_text, temperature=0.7, max_new_tokens=20):
|
|
43 |
top_p=0.9,
|
44 |
temperature=temperature,
|
45 |
num_return_sequences=3,
|
46 |
-
eos_token_id=tokenizer.eos_token_id
|
47 |
)
|
48 |
|
49 |
try:
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
except Exception as e:
|
55 |
st.error(f"Error durante la generaci贸n: {e}")
|
56 |
return "Error en la generaci贸n de texto."
|
@@ -63,20 +61,28 @@ def main():
|
|
63 |
if uploaded_file is not None:
|
64 |
df = pd.read_csv(uploaded_file)
|
65 |
query = 'aspiring human resources specialist'
|
66 |
-
|
67 |
if 'job_title' in df.columns:
|
68 |
-
job_titles = df['job_title']
|
69 |
|
70 |
# Definir el prompt con in-context learning
|
71 |
initial_prompt = (
|
72 |
-
|
73 |
-
f"
|
74 |
-
f"
|
75 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
)
|
77 |
|
|
|
78 |
st.write("Prompt inicial con In-context Learning:\n")
|
79 |
st.write(initial_prompt)
|
|
|
80 |
|
81 |
if st.button("Generar respuesta"):
|
82 |
with st.spinner("Generando respuesta..."):
|
@@ -96,4 +102,4 @@ def main():
|
|
96 |
st.error("La columna 'job_title' no se encuentra en el archivo CSV.")
|
97 |
|
98 |
if __name__ == "__main__":
|
99 |
-
main()
|
|
|
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"]
|
|
|
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:]
|
|
|
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."
|
|
|
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..."):
|
|
|
102 |
st.error("La columna 'job_title' no se encuentra en el archivo CSV.")
|
103 |
|
104 |
if __name__ == "__main__":
|
105 |
+
main()
|