Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,13 +1,9 @@
|
|
1 |
import streamlit as st
|
2 |
-
from transformers import
|
3 |
from huggingface_hub import login
|
4 |
import PyPDF2
|
5 |
import pandas as pd
|
6 |
import torch
|
7 |
-
import torch.nn as nn # Added this import
|
8 |
-
import numpy as np
|
9 |
-
from copy import deepcopy
|
10 |
-
import math
|
11 |
import time
|
12 |
|
13 |
# Device setup
|
@@ -21,7 +17,7 @@ st.set_page_config(
|
|
21 |
)
|
22 |
|
23 |
# Model name
|
24 |
-
MODEL_NAME = "deepseek-ai/DeepSeek-V3-0324"
|
25 |
|
26 |
# Translation prompt template
|
27 |
TRANSLATION_PROMPT = """
|
@@ -74,234 +70,6 @@ def process_file(uploaded_file):
|
|
74 |
st.error(f"📄 Error processing file: {str(e)}")
|
75 |
return ""
|
76 |
|
77 |
-
# Custom model definition
|
78 |
-
# Masking functions
|
79 |
-
def subsequent_mask(size):
|
80 |
-
attn_shape = (1, size, size)
|
81 |
-
subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')
|
82 |
-
return torch.from_numpy(subsequent_mask) == 0
|
83 |
-
|
84 |
-
def make_std_mask(tgt, pad):
|
85 |
-
tgt_mask = (tgt != pad).unsqueeze(-2)
|
86 |
-
return tgt_mask & subsequent_mask(tgt.size(-1)).type_as(tgt_mask.data)
|
87 |
-
|
88 |
-
# Batch class
|
89 |
-
class Batch:
|
90 |
-
def __init__(self, src, trg=None, pad=0):
|
91 |
-
src = torch.from_numpy(src).to(DEVICE).long()
|
92 |
-
self.src = src
|
93 |
-
self.src_mask = (src != pad).unsqueeze(-2)
|
94 |
-
if trg is not None:
|
95 |
-
trg = torch.from_numpy(trg).to(DEVICE).long()
|
96 |
-
self.trg = trg[:, :-1]
|
97 |
-
self.trg_y = trg[:, 1:]
|
98 |
-
self.trg_mask = make_std_mask(self.trg, pad)
|
99 |
-
self.ntokens = (self.trg_y != pad).data.sum()
|
100 |
-
|
101 |
-
# Hugging Face config
|
102 |
-
class En2FrConfig(PretrainedConfig):
|
103 |
-
model_type = "en2fr_transformer"
|
104 |
-
def __init__(self, src_vocab=32000, tgt_vocab=32000, N=6, d_model=512,
|
105 |
-
d_ff=2048, h=8, dropout=0.1, **kwargs):
|
106 |
-
self.src_vocab = src_vocab
|
107 |
-
self.tgt_vocab = tgt_vocab
|
108 |
-
self.N = N
|
109 |
-
self.d_model = d_model
|
110 |
-
self.d_ff = d_ff
|
111 |
-
self.h = h
|
112 |
-
self.dropout = dropout
|
113 |
-
super().__init__(**kwargs)
|
114 |
-
|
115 |
-
# Transformer components
|
116 |
-
class Transformer(nn.Module):
|
117 |
-
def __init__(self, encoder, decoder, src_embed, tgt_embed, generator):
|
118 |
-
super().__init__()
|
119 |
-
self.encoder = encoder
|
120 |
-
self.decoder = decoder
|
121 |
-
self.src_embed = src_embed
|
122 |
-
self.tgt_embed = tgt_embed
|
123 |
-
self.generator = generator
|
124 |
-
|
125 |
-
def forward(self, src, tgt, src_mask, tgt_mask):
|
126 |
-
memory = self.encoder(self.src_embed(src), src_mask)
|
127 |
-
output = self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask)
|
128 |
-
return output
|
129 |
-
|
130 |
-
class Encoder(nn.Module):
|
131 |
-
def __init__(self, layer, N):
|
132 |
-
super().__init__()
|
133 |
-
self.layers = nn.ModuleList([deepcopy(layer) for _ in range(N)])
|
134 |
-
self.norm = LayerNorm(layer.size)
|
135 |
-
|
136 |
-
def forward(self, x, mask):
|
137 |
-
for layer in self.layers:
|
138 |
-
x = layer(x, mask)
|
139 |
-
return self.norm(x)
|
140 |
-
|
141 |
-
class EncoderLayer(nn.Module):
|
142 |
-
def __init__(self, size, self_attn, feed_forward, dropout):
|
143 |
-
super().__init__()
|
144 |
-
self.self_attn = self_attn
|
145 |
-
self.feed_forward = feed_forward
|
146 |
-
self.sublayer = nn.ModuleList([deepcopy(SublayerConnection(size, dropout)) for _ in range(2)])
|
147 |
-
self.size = size
|
148 |
-
|
149 |
-
def forward(self, x, mask):
|
150 |
-
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
|
151 |
-
return self.sublayer[1](x, self.feed_forward)
|
152 |
-
|
153 |
-
class Decoder(nn.Module):
|
154 |
-
def __init__(self, layer, N):
|
155 |
-
super().__init__()
|
156 |
-
self.layers = nn.ModuleList([deepcopy(layer) for _ in range(N)])
|
157 |
-
self.norm = LayerNorm(layer.size)
|
158 |
-
|
159 |
-
def forward(self, x, memory, src_mask, tgt_mask):
|
160 |
-
for layer in self.layers:
|
161 |
-
x = layer(x, memory, src_mask, tgt_mask)
|
162 |
-
return self.norm(x)
|
163 |
-
|
164 |
-
class DecoderLayer(nn.Module):
|
165 |
-
def __init__(self, size, self_attn, src_attn, feed_forward, dropout):
|
166 |
-
super().__init__()
|
167 |
-
self.size = size
|
168 |
-
self.self_attn = self_attn
|
169 |
-
self.src_attn = src_attn
|
170 |
-
self.feed_forward = feed_forward
|
171 |
-
self.sublayer = nn.ModuleList([deepcopy(SublayerConnection(size, dropout)) for _ in range(3)])
|
172 |
-
|
173 |
-
def forward(self, x, memory, src_mask, tgt_mask):
|
174 |
-
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask))
|
175 |
-
x = self.sublayer[1](x, lambda x: self.src_attn(x, memory, memory, src_mask))
|
176 |
-
return self.sublayer[2](x, self.feed_forward)
|
177 |
-
|
178 |
-
class SublayerConnection(nn.Module):
|
179 |
-
def __init__(self, size, dropout):
|
180 |
-
super().__init__()
|
181 |
-
self.norm = LayerNorm(size)
|
182 |
-
self.dropout = nn.Dropout(dropout)
|
183 |
-
|
184 |
-
def forward(self, x, sublayer):
|
185 |
-
return x + self.dropout(sublayer(self.norm(x)))
|
186 |
-
|
187 |
-
class LayerNorm(nn.Module):
|
188 |
-
def __init__(self, features, eps=1e-6):
|
189 |
-
super().__init__()
|
190 |
-
self.a_2 = nn.Parameter(torch.ones(features))
|
191 |
-
self.b_2 = nn.Parameter(torch.zeros(features))
|
192 |
-
self.eps = eps
|
193 |
-
|
194 |
-
def forward(self, x):
|
195 |
-
mean = x.mean(-1, keepdim=True)
|
196 |
-
std = x.std(-1, keepdim=True)
|
197 |
-
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
|
198 |
-
|
199 |
-
class MultiHeadedAttention(nn.Module):
|
200 |
-
def __init__(self, h, d_model, dropout=0.1):
|
201 |
-
super().__init__()
|
202 |
-
assert d_model % h == 0
|
203 |
-
self.d_k = d_model // h
|
204 |
-
self.h = h
|
205 |
-
self.linears = nn.ModuleList([deepcopy(nn.Linear(d_model, d_model)) for _ in range(4)])
|
206 |
-
self.attn = None
|
207 |
-
self.dropout = nn.Dropout(p=dropout)
|
208 |
-
|
209 |
-
def forward(self, query, key, value, mask=None):
|
210 |
-
if mask is not None:
|
211 |
-
mask = mask.unsqueeze(1)
|
212 |
-
nbatches = query.size(0)
|
213 |
-
query, key, value = [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
|
214 |
-
for l, x in zip(self.linears, (query, key, value))]
|
215 |
-
x, self.attn = attention(query, key, value, mask=mask, dropout=self.dropout)
|
216 |
-
x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k)
|
217 |
-
return self.linears[-1](x)
|
218 |
-
|
219 |
-
def attention(query, key, value, mask=None, dropout=None):
|
220 |
-
d_k = query.size(-1)
|
221 |
-
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)
|
222 |
-
if mask is not None:
|
223 |
-
scores = scores.masked_fill(mask == 0, -1e9)
|
224 |
-
p_attn = nn.functional.softmax(scores, dim=-1)
|
225 |
-
if dropout is not None:
|
226 |
-
p_attn = dropout(p_attn)
|
227 |
-
return torch.matmul(p_attn, value), p_attn
|
228 |
-
|
229 |
-
class PositionwiseFeedForward(nn.Module):
|
230 |
-
def __init__(self, d_model, d_ff, dropout=0.1):
|
231 |
-
super().__init__()
|
232 |
-
self.w_1 = nn.Linear(d_model, d_ff)
|
233 |
-
self.w_2 = nn.Linear(d_ff, d_model)
|
234 |
-
self.dropout = nn.Dropout(dropout)
|
235 |
-
|
236 |
-
def forward(self, x):
|
237 |
-
return self.w_2(self.dropout(self.w_1(x)))
|
238 |
-
|
239 |
-
class Embeddings(nn.Module):
|
240 |
-
def __init__(self, d_model, vocab):
|
241 |
-
super().__init__()
|
242 |
-
self.lut = nn.Embedding(vocab, d_model)
|
243 |
-
self.d_model = d_model
|
244 |
-
|
245 |
-
def forward(self, x):
|
246 |
-
return self.lut(x) * math.sqrt(self.d_model)
|
247 |
-
|
248 |
-
class PositionalEncoding(nn.Module):
|
249 |
-
def __init__(self, d_model, dropout, max_len=5000):
|
250 |
-
super().__init__()
|
251 |
-
self.dropout = nn.Dropout(p=dropout)
|
252 |
-
pe = torch.zeros(max_len, d_model, device=DEVICE)
|
253 |
-
position = torch.arange(0., max_len, device=DEVICE).unsqueeze(1)
|
254 |
-
div_term = torch.exp(torch.arange(0., d_model, 2, device=DEVICE) * -(math.log(10000.0) / d_model))
|
255 |
-
pe[:, 0::2] = torch.sin(position * div_term)
|
256 |
-
pe[:, 1::2] = torch.cos(position * div_term)
|
257 |
-
pe = pe.unsqueeze(0)
|
258 |
-
self.register_buffer('pe', pe)
|
259 |
-
|
260 |
-
def forward(self, x):
|
261 |
-
x = x + self.pe[:, :x.size(1)].requires_grad_(False)
|
262 |
-
return self.dropout(x)
|
263 |
-
|
264 |
-
class Generator(nn.Module):
|
265 |
-
def __init__(self, d_model, vocab):
|
266 |
-
super().__init__()
|
267 |
-
self.proj = nn.Linear(d_model, vocab)
|
268 |
-
|
269 |
-
def forward(self, x):
|
270 |
-
return nn.functional.log_softmax(self.proj(x), dim=-1)
|
271 |
-
|
272 |
-
def create_model(src_vocab, tgt_vocab, N, d_model, d_ff, h, dropout=0.1):
|
273 |
-
attn = MultiHeadedAttention(h, d_model).to(DEVICE)
|
274 |
-
ff = PositionwiseFeedForward(d_model, d_ff, dropout).to(DEVICE)
|
275 |
-
pos = PositionalEncoding(d_model, dropout).to(DEVICE)
|
276 |
-
model = Transformer(
|
277 |
-
Encoder(EncoderLayer(d_model, deepcopy(attn), deepcopy(ff), dropout).to(DEVICE), N).to(DEVICE),
|
278 |
-
Decoder(DecoderLayer(d_model, deepcopy(attn), deepcopy(attn), deepcopy(ff), dropout).to(DEVICE), N).to(DEVICE),
|
279 |
-
nn.Sequential(Embeddings(d_model, src_vocab).to(DEVICE), deepcopy(pos)),
|
280 |
-
nn.Sequential(Embeddings(d_model, tgt_vocab).to(DEVICE), deepcopy(pos)),
|
281 |
-
Generator(d_model, tgt_vocab)).to(DEVICE)
|
282 |
-
for p in model.parameters():
|
283 |
-
if p.dim() > 1:
|
284 |
-
nn.init.xavier_uniform_(p)
|
285 |
-
return model
|
286 |
-
|
287 |
-
class En2FrTransformer(PreTrainedModel):
|
288 |
-
config_class = En2FrConfig
|
289 |
-
|
290 |
-
def __init__(self, config):
|
291 |
-
super().__init__(config)
|
292 |
-
self.model = create_model(
|
293 |
-
src_vocab=config.src_vocab,
|
294 |
-
tgt_vocab=config.tgt_vocab,
|
295 |
-
N=config.N,
|
296 |
-
d_model=config.d_model,
|
297 |
-
d_ff=config.d_ff,
|
298 |
-
h=config.h,
|
299 |
-
dropout=config.dropout
|
300 |
-
)
|
301 |
-
|
302 |
-
def forward(self, src, tgt, src_mask, tgt_mask):
|
303 |
-
return self.model(src, tgt, src_mask, tgt_mask)
|
304 |
-
|
305 |
# Model loading function
|
306 |
@st.cache_resource
|
307 |
def load_model(hf_token):
|
@@ -312,15 +80,18 @@ def load_model(hf_token):
|
|
312 |
|
313 |
login(token=hf_token)
|
314 |
|
315 |
-
# Load tokenizer
|
316 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=hf_token)
|
317 |
|
318 |
-
# Load the
|
319 |
-
|
|
|
320 |
MODEL_NAME,
|
321 |
-
token=hf_token
|
|
|
|
|
|
|
322 |
)
|
323 |
-
model.to(DEVICE) # Ensure model is on the correct device
|
324 |
|
325 |
return model, tokenizer
|
326 |
|
@@ -328,40 +99,39 @@ def load_model(hf_token):
|
|
328 |
st.error(f"🤖 Model loading failed: {str(e)}")
|
329 |
return None
|
330 |
|
331 |
-
#
|
332 |
-
def tokenize_text(text, tokenizer, max_length=10):
|
333 |
-
# This is a placeholder; in a real scenario, you'd use the tokenizer's vocabulary
|
334 |
-
# For now, we'll create dummy token IDs (0 for padding, 1 for start, 2 for end, 3+ for words)
|
335 |
-
words = text.split()
|
336 |
-
token_ids = [1] + [i + 3 for i in range(min(len(words), max_length - 2))] + [2]
|
337 |
-
if len(token_ids) < max_length:
|
338 |
-
token_ids += [0] * (max_length - len(token_ids))
|
339 |
-
return torch.tensor([token_ids], dtype=torch.long, device=DEVICE)
|
340 |
-
|
341 |
-
# Generation function for translation (custom inference loop)
|
342 |
def generate_translation(input_text, model, tokenizer):
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
350 |
|
351 |
-
#
|
352 |
-
|
353 |
-
tgt_mask = make_std_mask(tgt, pad=0)
|
354 |
-
output = model(src, tgt, src_mask, tgt_mask)
|
355 |
-
output = model.model.generator(output[:, -1, :]) # Get logits for the last token
|
356 |
-
next_token = torch.argmax(output, dim=-1).unsqueeze(0)
|
357 |
-
tgt = torch.cat((tgt, next_token), dim=1)
|
358 |
-
if next_token.item() == 2: # End token
|
359 |
-
break
|
360 |
|
361 |
-
#
|
362 |
-
|
363 |
-
translation = " ".join([f"word{i-3}" if i >= 3 else "<start>" if i == 1 else "<end>" for i in tgt[0].tolist()])
|
364 |
return translation
|
|
|
|
|
|
|
365 |
|
366 |
# Display chat messages
|
367 |
for message in st.session_state.messages:
|
@@ -411,10 +181,10 @@ if prompt := st.chat_input("Enter text to translate into French..."):
|
|
411 |
st.markdown(translation)
|
412 |
st.session_state.messages.append({"role": "assistant", "content": translation})
|
413 |
|
414 |
-
# Calculate performance metrics
|
415 |
end_time = time.time()
|
416 |
-
input_tokens = len(input_text
|
417 |
-
output_tokens = len(translation
|
418 |
speed = output_tokens / (end_time - start_time)
|
419 |
|
420 |
# Calculate costs (hypothetical pricing model)
|
|
|
1 |
import streamlit as st
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
3 |
from huggingface_hub import login
|
4 |
import PyPDF2
|
5 |
import pandas as pd
|
6 |
import torch
|
|
|
|
|
|
|
|
|
7 |
import time
|
8 |
|
9 |
# Device setup
|
|
|
17 |
)
|
18 |
|
19 |
# Model name
|
20 |
+
MODEL_NAME = "deepseek-ai/DeepSeek-V3-0324"
|
21 |
|
22 |
# Translation prompt template
|
23 |
TRANSLATION_PROMPT = """
|
|
|
70 |
st.error(f"📄 Error processing file: {str(e)}")
|
71 |
return ""
|
72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
# Model loading function
|
74 |
@st.cache_resource
|
75 |
def load_model(hf_token):
|
|
|
80 |
|
81 |
login(token=hf_token)
|
82 |
|
83 |
+
# Load tokenizer
|
84 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=hf_token)
|
85 |
|
86 |
+
# Load the model with appropriate dtype for CPU/GPU compatibility
|
87 |
+
dtype = torch.float16 if DEVICE == "cuda" else torch.float32
|
88 |
+
model = AutoModelForCausalLM.from_pretrained(
|
89 |
MODEL_NAME,
|
90 |
+
token=hf_token,
|
91 |
+
torch_dtype=dtype,
|
92 |
+
device_map="auto", # Automatically maps to CPU or GPU
|
93 |
+
quantization_config=None # Disable FP8 quantization
|
94 |
)
|
|
|
95 |
|
96 |
return model, tokenizer
|
97 |
|
|
|
99 |
st.error(f"🤖 Model loading failed: {str(e)}")
|
100 |
return None
|
101 |
|
102 |
+
# Generation function for translation
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
def generate_translation(input_text, model, tokenizer):
|
104 |
+
try:
|
105 |
+
# Prepare the prompt
|
106 |
+
full_prompt = TRANSLATION_PROMPT.format(input_text=input_text)
|
107 |
+
|
108 |
+
# Tokenize the input
|
109 |
+
inputs = tokenizer(full_prompt, return_tensors="pt", padding=True, truncation=True, max_length=512)
|
110 |
+
inputs = inputs.to(DEVICE)
|
111 |
+
|
112 |
+
# Generate translation
|
113 |
+
model.eval()
|
114 |
+
with torch.no_grad():
|
115 |
+
outputs = model.generate(
|
116 |
+
input_ids=inputs["input_ids"],
|
117 |
+
attention_mask=inputs["attention_mask"],
|
118 |
+
max_new_tokens=512,
|
119 |
+
temperature=0.7,
|
120 |
+
top_p=0.9,
|
121 |
+
repetition_penalty=1.1,
|
122 |
+
do_sample=True,
|
123 |
+
num_return_sequences=1
|
124 |
+
)
|
125 |
|
126 |
+
# Decode the output
|
127 |
+
translation = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
|
129 |
+
# Extract the French translation part (after the prompt)
|
130 |
+
translation = translation.split("**French translation:**")[-1].strip()
|
|
|
131 |
return translation
|
132 |
+
|
133 |
+
except Exception as e:
|
134 |
+
raise Exception(f"Generation error: {str(e)}")
|
135 |
|
136 |
# Display chat messages
|
137 |
for message in st.session_state.messages:
|
|
|
181 |
st.markdown(translation)
|
182 |
st.session_state.messages.append({"role": "assistant", "content": translation})
|
183 |
|
184 |
+
# Calculate performance metrics
|
185 |
end_time = time.time()
|
186 |
+
input_tokens = len(tokenizer(input_text)["input_ids"])
|
187 |
+
output_tokens = len(tokenizer(translation)["input_ids"])
|
188 |
speed = output_tokens / (end_time - start_time)
|
189 |
|
190 |
# Calculate costs (hypothetical pricing model)
|