Update app.py
Browse files
app.py
CHANGED
@@ -1,137 +1,58 @@
|
|
1 |
import streamlit as st
|
2 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
|
3 |
-
from huggingface_hub import login
|
4 |
-
from threading import Thread
|
5 |
-
import PyPDF2
|
6 |
-
import pandas as pd
|
7 |
import torch
|
8 |
import time
|
9 |
import os
|
10 |
-
from
|
11 |
-
|
12 |
-
|
13 |
-
# Check if 'peft' is installed
|
14 |
-
try:
|
15 |
-
from peft import PeftModel, PeftConfig
|
16 |
-
except ImportError:
|
17 |
-
raise ImportError(
|
18 |
-
"The 'peft' library is required but not installed. "
|
19 |
-
"Please install it using: `pip install peft`"
|
20 |
-
)
|
21 |
-
|
22 |
-
# π Hardcoded Hugging Face Token
|
23 |
|
24 |
-
|
|
|
25 |
|
26 |
-
#
|
27 |
st.set_page_config(
|
28 |
-
page_title="
|
29 |
page_icon="π",
|
30 |
layout="centered"
|
31 |
)
|
32 |
|
33 |
-
|
34 |
-
BASE_MODEL_NAME = "NousResearch/Nous-Hermes-2-Mistral-7B-DPO" #"neuralmind/bert-base-portuguese-cased" #"pierreguillou/gpt2-small-portuguese" #"unicamp-dl/ptt5-base-portuguese-vocab" #"mistralai/Mistral-7B-Instruct-v0.2"
|
35 |
-
MODEL_OPTIONS = {
|
36 |
-
"Full Fine-Tuned": "amiguel/GM_finetune", #"amiguel/mistral-angolan-laborlaw-bert-base-pt", #"amiguel/mistral-angolan-laborlaw-gpt2",#"amiguel/mistral-angolan-laborlaw-ptt5", #"amiguel/mistral-angolan-laborlaw",
|
37 |
-
"LoRA Adapter": "amiguel/SmolLM2-360M-concise-reasoning-lora",
|
38 |
-
"QLoRA Adapter": "amiguel/SmolLM2-360M-concise-reasoning-qlora"
|
39 |
-
}
|
40 |
-
|
41 |
-
st.title("π Assistente | Angola π")
|
42 |
|
|
|
43 |
USER_AVATAR = "https://raw.githubusercontent.com/achilela/vila_fofoka_analysis/9904d9a0d445ab0488cf7395cb863cce7621d897/USER_AVATAR.png"
|
44 |
BOT_AVATAR = "https://raw.githubusercontent.com/achilela/vila_fofoka_analysis/991f4c6e4e1dc7a8e24876ca5aae5228bcdb4dba/Ataliba_Avatar.jpg"
|
45 |
|
46 |
-
#
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
"
|
55 |
-
|
56 |
-
|
|
|
57 |
)
|
|
|
|
|
|
|
58 |
|
59 |
# Session state
|
60 |
if "messages" not in st.session_state:
|
61 |
st.session_state.messages = []
|
62 |
|
63 |
-
#
|
64 |
-
|
65 |
-
def process_file(uploaded_file):
|
66 |
-
if uploaded_file is None:
|
67 |
-
return ""
|
68 |
-
|
69 |
-
try:
|
70 |
-
if uploaded_file.type == "application/pdf":
|
71 |
-
pdf_reader = PyPDF2.PdfReader(uploaded_file)
|
72 |
-
return "\n".join([page.extract_text() for page in pdf_reader.pages])
|
73 |
-
elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
|
74 |
-
df = pd.read_excel(uploaded_file)
|
75 |
-
return df.to_markdown()
|
76 |
-
except Exception as e:
|
77 |
-
st.error(f"π Error processing file: {str(e)}")
|
78 |
-
return ""
|
79 |
-
|
80 |
-
# Model loader
|
81 |
-
@st.cache_resource
|
82 |
-
def load_model(model_type, selected_model):
|
83 |
-
try:
|
84 |
-
login(token=HF_TOKEN)
|
85 |
-
|
86 |
-
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_NAME, token=HF_TOKEN)
|
87 |
-
|
88 |
-
if model_type == "Full Fine-Tuned":
|
89 |
-
|
90 |
-
model = AutoModelForMaskedLM.from_pretrained(
|
91 |
-
selected_model,
|
92 |
-
torch_dtype=torch.bfloat16, # or float32 for compatibility
|
93 |
-
token=HF_TOKEN
|
94 |
-
).to("cuda" if torch.cuda.is_available() else "cpu")
|
95 |
-
|
96 |
-
#model = AutoModelForCausalLM.from_pretrained(
|
97 |
-
#selected_model,
|
98 |
-
# torch_dtype=torch.bfloat16,
|
99 |
-
# device_map="auto",
|
100 |
-
# token=HF_TOKEN
|
101 |
-
#
|
102 |
-
|
103 |
-
else:
|
104 |
-
base_model = AutoModelForCausalLM.from_pretrained(
|
105 |
-
BASE_MODEL_NAME,
|
106 |
-
torch_dtype=torch.bfloat16,
|
107 |
-
device_map="auto",
|
108 |
-
token=HF_TOKEN
|
109 |
-
)
|
110 |
-
model = PeftModel.from_pretrained(
|
111 |
-
base_model,
|
112 |
-
selected_model,
|
113 |
-
torch_dtype=torch.bfloat16,
|
114 |
-
is_trainable=False,
|
115 |
-
token=HF_TOKEN
|
116 |
-
)
|
117 |
-
return model, tokenizer
|
118 |
-
|
119 |
-
except Exception as e:
|
120 |
-
st.error(f"π€ Model loading failed: {str(e)}")
|
121 |
-
return None
|
122 |
-
|
123 |
-
# Generation function
|
124 |
-
def generate_with_kv_cache(prompt, file_context, model, tokenizer, use_cache=True):
|
125 |
-
full_prompt = f"Analyze this context:\n{file_context}\n\nQuestion: {prompt}\nAnswer:"
|
126 |
-
|
127 |
streamer = TextIteratorStreamer(
|
128 |
-
tokenizer,
|
129 |
-
skip_prompt=True,
|
130 |
skip_special_tokens=True
|
131 |
)
|
132 |
-
|
133 |
-
inputs = tokenizer(
|
134 |
-
|
135 |
generation_kwargs = {
|
136 |
"input_ids": inputs["input_ids"],
|
137 |
"attention_mask": inputs["attention_mask"],
|
@@ -140,11 +61,11 @@ def generate_with_kv_cache(prompt, file_context, model, tokenizer, use_cache=Tru
|
|
140 |
"top_p": 0.9,
|
141 |
"repetition_penalty": 1.1,
|
142 |
"do_sample": True,
|
143 |
-
"use_cache": use_cache,
|
144 |
"streamer": streamer
|
145 |
}
|
146 |
-
|
147 |
-
Thread(target=model.generate, kwargs=generation_kwargs)
|
|
|
148 |
return streamer
|
149 |
|
150 |
# Display chat history
|
@@ -153,40 +74,26 @@ for message in st.session_state.messages:
|
|
153 |
with st.chat_message(message["role"], avatar=avatar):
|
154 |
st.markdown(message["content"])
|
155 |
|
156 |
-
#
|
157 |
-
if prompt := st.chat_input("Ask
|
158 |
-
|
159 |
-
# Load model if necessary
|
160 |
-
if "model" not in st.session_state or st.session_state.get("model_type") != model_type:
|
161 |
-
model_data = load_model(model_type, selected_model)
|
162 |
-
if model_data is None:
|
163 |
-
st.error("Failed to load model.")
|
164 |
-
st.stop()
|
165 |
-
|
166 |
-
st.session_state.model, st.session_state.tokenizer = model_data
|
167 |
-
st.session_state.model_type = model_type
|
168 |
-
|
169 |
-
model = st.session_state.model
|
170 |
-
tokenizer = st.session_state.tokenizer
|
171 |
|
|
|
172 |
with st.chat_message("user", avatar=USER_AVATAR):
|
173 |
st.markdown(prompt)
|
174 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
175 |
|
176 |
-
|
177 |
-
|
178 |
if model and tokenizer:
|
179 |
try:
|
180 |
with st.chat_message("assistant", avatar=BOT_AVATAR):
|
181 |
start_time = time.time()
|
182 |
-
streamer =
|
183 |
|
184 |
response_container = st.empty()
|
185 |
full_response = ""
|
186 |
|
187 |
for chunk in streamer:
|
188 |
-
|
189 |
-
full_response += cleaned_chunk + " "
|
190 |
response_container.markdown(full_response + "β", unsafe_allow_html=True)
|
191 |
|
192 |
end_time = time.time()
|
@@ -194,15 +101,9 @@ if prompt := st.chat_input("Ask your inspection question..."):
|
|
194 |
output_tokens = len(tokenizer(full_response)["input_ids"])
|
195 |
speed = output_tokens / (end_time - start_time)
|
196 |
|
197 |
-
input_cost = (input_tokens / 1_000_000) * 5
|
198 |
-
output_cost = (output_tokens / 1_000_000) * 15
|
199 |
-
total_cost_usd = input_cost + output_cost
|
200 |
-
total_cost_aoa = total_cost_usd * 1160
|
201 |
-
|
202 |
st.caption(
|
203 |
f"π Input Tokens: {input_tokens} | Output Tokens: {output_tokens} | "
|
204 |
-
f"π Speed: {speed:.1f}
|
205 |
-
f"π΅ Cost (AOA): {total_cost_aoa:.4f}"
|
206 |
)
|
207 |
|
208 |
response_container.markdown(full_response)
|
|
|
1 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
2 |
import torch
|
3 |
import time
|
4 |
import os
|
5 |
+
from threading import Thread
|
6 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
|
7 |
+
from huggingface_hub import login
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
+
# Hardcoded Hugging Face Token
|
10 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") # or directly "hf_xxxxxx"
|
11 |
|
12 |
+
# App config
|
13 |
st.set_page_config(
|
14 |
+
page_title="GM Fine-tune Assistant π",
|
15 |
page_icon="π",
|
16 |
layout="centered"
|
17 |
)
|
18 |
|
19 |
+
st.title("π GM Fine-tune Assistant π")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
+
# Avatars
|
22 |
USER_AVATAR = "https://raw.githubusercontent.com/achilela/vila_fofoka_analysis/9904d9a0d445ab0488cf7395cb863cce7621d897/USER_AVATAR.png"
|
23 |
BOT_AVATAR = "https://raw.githubusercontent.com/achilela/vila_fofoka_analysis/991f4c6e4e1dc7a8e24876ca5aae5228bcdb4dba/Ataliba_Avatar.jpg"
|
24 |
|
25 |
+
# Login to Huggingface
|
26 |
+
login(token=HF_TOKEN)
|
27 |
+
|
28 |
+
# Load Model
|
29 |
+
@st.cache_resource
|
30 |
+
def load_model():
|
31 |
+
tokenizer = AutoTokenizer.from_pretrained("amiguel/GM_finetune", token=HF_TOKEN)
|
32 |
+
model = AutoModelForCausalLM.from_pretrained(
|
33 |
+
"amiguel/GM_finetune",
|
34 |
+
device_map="auto",
|
35 |
+
torch_dtype=torch.bfloat16,
|
36 |
+
token=HF_TOKEN
|
37 |
)
|
38 |
+
return model, tokenizer
|
39 |
+
|
40 |
+
model, tokenizer = load_model()
|
41 |
|
42 |
# Session state
|
43 |
if "messages" not in st.session_state:
|
44 |
st.session_state.messages = []
|
45 |
|
46 |
+
# Streamer
|
47 |
+
def generate_response(prompt, model, tokenizer):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
streamer = TextIteratorStreamer(
|
49 |
+
tokenizer,
|
50 |
+
skip_prompt=True,
|
51 |
skip_special_tokens=True
|
52 |
)
|
53 |
+
|
54 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
55 |
+
|
56 |
generation_kwargs = {
|
57 |
"input_ids": inputs["input_ids"],
|
58 |
"attention_mask": inputs["attention_mask"],
|
|
|
61 |
"top_p": 0.9,
|
62 |
"repetition_penalty": 1.1,
|
63 |
"do_sample": True,
|
|
|
64 |
"streamer": streamer
|
65 |
}
|
66 |
+
|
67 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
68 |
+
thread.start()
|
69 |
return streamer
|
70 |
|
71 |
# Display chat history
|
|
|
74 |
with st.chat_message(message["role"], avatar=avatar):
|
75 |
st.markdown(message["content"])
|
76 |
|
77 |
+
# Chat input
|
78 |
+
if prompt := st.chat_input("Ask me anything about General Knowledge..."):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
|
80 |
+
# Display user message
|
81 |
with st.chat_message("user", avatar=USER_AVATAR):
|
82 |
st.markdown(prompt)
|
83 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
84 |
|
85 |
+
# Bot generating response
|
|
|
86 |
if model and tokenizer:
|
87 |
try:
|
88 |
with st.chat_message("assistant", avatar=BOT_AVATAR):
|
89 |
start_time = time.time()
|
90 |
+
streamer = generate_response(prompt, model, tokenizer)
|
91 |
|
92 |
response_container = st.empty()
|
93 |
full_response = ""
|
94 |
|
95 |
for chunk in streamer:
|
96 |
+
full_response += chunk
|
|
|
97 |
response_container.markdown(full_response + "β", unsafe_allow_html=True)
|
98 |
|
99 |
end_time = time.time()
|
|
|
101 |
output_tokens = len(tokenizer(full_response)["input_ids"])
|
102 |
speed = output_tokens / (end_time - start_time)
|
103 |
|
|
|
|
|
|
|
|
|
|
|
104 |
st.caption(
|
105 |
f"π Input Tokens: {input_tokens} | Output Tokens: {output_tokens} | "
|
106 |
+
f"π Speed: {speed:.1f} tokens/sec"
|
|
|
107 |
)
|
108 |
|
109 |
response_container.markdown(full_response)
|