Spaces:
Runtime error
Runtime error
Update app.py
Browse files12322 unmodified lines2627282930319 unmodified lines414243444546474849505152535455562 unmodified lines59606162636465666768697 unmodified lines7778798081828384858687889 unmodified lines98991001011021031041051064 unmodified lines1111121131141151161 unmodified line1181191201211221231241251 unmodified line12712812913013113213313413513613713813914014114214314414522 unmodified lines1681691701711721731748 unmodified lines18318418518618718818919019119219319419520 unmodified lines21621721821922022122222322422522622722822923023123223323423523623723823931 unmodified lines2712722732742752762778 unmodified lines28628728828929029129219 unmodified lines3123133143153163173187 unmodified lines3263273283293303313323333343353363373383393403413423433443453461 unmodified line34834935035135235335435535635735835936036136236336436536636710 unmodified lines3783793803813823833843853863878 unmodified lines3963973983994004014024034044054064074084094102 unmodified lines413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496import osimport mathimport re22 unmodified linesself.word2index = {self.PAD: 0, self.SOS: 1, self.EOS: 2, self.UNK: 3, self.SYSTEM: 4}self.index2word = {0: self.PAD, 1: self.SOS, 2: self.EOS, 3: self.UNK, 4: self.SYSTEM}self.n_words = 5@staticmethoddef load_from_checkpoint(checkpoint):voc = Voc()9 unmodified linesvoc.SYSTEM = tokens.get("SYSTEM", "<SYSTEM>")return voc# English-only sanitation:# Define characters that should stick to words (letters, digits, apostrophe, hyphen)_WORD_TOKEN_CHARS = r"a-z0-9\'\-"# Define punctuation that should be split as separate tokens (e.g., comma, period, question mark)_SPLIT_PUNCT = r"\.\,\!\?\:\;\(\)\[\]\{\}\"\/\\@#\$%\^&\*\+\<>=~`"_token_re = re.compile(rf"[{_WORD_TOKEN_CHARS}]+|[{_SPLIT_PUNCT}]", flags=re.IGNORECASE)def to_ascii(text: str) -> str:# Normalize and remove non-ASCIItext = unicodedata.normalize("NFKC", text)return text.encode("ascii", errors="ignore").decode("ascii")2 unmodified linesreturn _token_re.findall(ascii_text)def is_english_like(text: str, min_alpha_ratio: float = 0.6, max_non_ascii: int = 0):"""Heuristic:- Must have <= max_non_ascii non-ASCII after normalization (we remove them, but check original).- After ASCII filtering, the ratio of letters to total characters should be high enough."""norm = unicodedata.normalize("NFKC", text)non_ascii_count = sum(1 for ch in norm if ord(ch) > 127)if non_ascii_count > max_non_ascii:7 unmodified linesreturn ratio >= min_alpha_ratiodef check_repetition(text: str, max_repeat: int = 2):"""Checks if any single token is repeated more than max_repeat times consecutively."""tokens = tokenize(text)if not tokens:return False# Check for consecutive triples (or more) of the same tokenfor i in range(len(tokens) - max_repeat):if all(tokens[i] == tokens[j] for j in range(i, i + max_repeat + 1)):return True9 unmodified linespe[:, 0::2] = torch.sin(position * div_term)pe[:, 1::2] = torch.cos(position * div_term)self.register_buffer("pe", pe.unsqueeze(0))def forward(self, x):return x + self.pe[:, : x.size(1), :]class GPT(nn.Module):def __init__(self, n_words, d_model, n_layers, n_head, d_ff, dropout=0.1):super().__init__()4 unmodified linesself.transformer = nn.TransformerEncoder(enc_layer, n_layers)self.fc = nn.Linear(d_model, n_words, bias=False)self.fc.weight = self.embedding.weightdef forward(self, x, mask=None, key_padding_mask=None):x = self.embedding(x)x = self.pos(x)1 unmodified lineout = self.transformer(x, mask=mask, src_key_padding_mask=key_padding_mask)return self.fc(out)def indexes_from_sentence(voc, sentence):# Sanitize to English-only before mapping to vocabsanitized = " ".join(tokenize(sentence))prompt_tokens = [voc.SYSTEM] + tokenize(sanitized)return [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in prompt_tokens] + [voc.word2index[voc.EOS]]1 unmodified linedef make_bool_causal_mask(sz, device):return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")CHECKPOINT_PATH = "checkpoint.pth"if not os.path.exists(CHECKPOINT_PATH):# NOTE: This is a placeholder for a real application setup.print("WARNING: Using dummy checkpoint as real file not found. Online learning will not affect model state permanently.")checkpoint = {"voc_word2index": Voc().word2index,"voc_index2word": Voc().index2word,"gpt_model_state_dict": None}# Placeholder for model initialization if checkpoint fails (for testing/safety)d_model = 768n_head = 48d_ff = 76822 unmodified linesgpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)if "gpt_model_state_dict" in checkpoint and checkpoint["gpt_model_state_dict"] is not None:gpt_model.load_state_dict(checkpoint["gpt_model_state_dict"], strict=True)optimizer = optim.Adam(gpt_model.parameters(), lr=LEARNING_RATE)criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])8 unmodified lineselse:return ""def online_update(model, input_sentence, target_response, max_seq_len, search_context="", conversation_context=""):"""Performs a fixed number of training steps (epochs), incorporating sanitized English-only search context."""is_response_clean = is_english_like(target_response, min_alpha_ratio=0.7) and not any(t in target_response for t in [voc.UNK, "i couldn't generate"])is_not_repetitive = not check_repetition(target_response, max_repeat=2)if not is_response_clean or not is_not_repetitive:print("Skipping online update: Target response is non-English, corrupted, or highly repetitive.")return20 unmodified linestarget_tensor = torch.tensor(target_ids, dtype=torch.long, device=device)L = input_tensor.size(1)model.train()causal = make_bool_causal_mask(L, device)last_loss = 0.0for epoch in range(ONLINE_LEARNING_EPOCHS):optimizer.zero_grad()logits = model(input_tensor, mask=causal, key_padding_mask=None)loss = criterion(logits.squeeze(0), target_tensor)loss.backward()optimizer.step()last_loss = loss.item()model.eval()print(f"Online update performed over {ONLINE_LEARNING_EPOCHS} epochs. Final Loss: {last_loss:.4f}")def generate_response(prompt, search_context="", conversation_context=""):if not is_english_like(prompt):return "Please use English. Non-English input was detected."31 unmodified linescandidate_word = voc.index2word.get(candidate_id, voc.UNK)token_ok = is_english_like(candidate_word, min_alpha_ratio=0.1, max_non_ascii=0)if candidate_id == voc.word2index[voc.EOS]:next_id = candidate_idbreak8 unmodified linesif next_id == voc.word2index[voc.EOS]:breakgenerated.append(next_id)input_tensor = torch.cat([input_tensor, torch.tensor([[next_id]], device=device, dtype=torch.long)],19 unmodified linesreturn history, "Cannot process feedback: No recent AI response found."last_user_message, last_ai_response = history[-1][0], history[-1][1]print(f"\n--- FEEDBACK RECEIVED ---")print(f"Rating: {rating}")print(f"User Prompt: '{last_user_message}'")7 unmodified linesconversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"online_update(gpt_model,last_user_message,last_ai_response,max_length,search_context="",conversation_context=conversation_context)feedback_message = f"Thanks for the **Good Response** rating! I just learned from that. Keep the good prompts coming! ✨"elif rating == "Bad Response":feedback_message = f"Acknowledged **Bad Response** feedback. I will try to be better! 🛠️"else:feedback_message = "Unknown rating received."return history, feedback_message1 unmodified line"""The central handler called by the front-end when the user submits a message."""# 1. Handle file upload (Placeholder)file_context = ""if uploaded_file:file_name = uploaded_file.name.split("/")[-1] # Gradio File object's pathfile_context = f"The user has provided a file named '{file_name}'. Analyze or respond to the user's prompt *about this file*."print(f"File attached: {file_name}")# 2. Determine if this is a regeneration/enhancement instructionis_instruction = any(user_message.lower().startswith(p) for p in ["please generate", "provide a much more detailed", "provide a different"])# 3. Extract the clean message for the model inputmatch = re.search(r':\s*"(.+?)"$', user_message)if is_instruction and match:clean_user_message = match.group(1).strip()model_prompt = user_message10 unmodified linesconversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"print(f"Context included: {conversation_context}")# 5. Enforce English-only input for the *clean* messageif not is_english_like(clean_user_message):# We assume the user message has already been added by the helper function,# so we just update the response field.history[-1][1] = "Please use English. Non-English input was detected."return history, ""8 unmodified lines# 7. Prepend file context (if any) to the model's promptfinal_model_prompt = f"{file_context} {model_prompt}" if file_context else model_prompt# 8. Generate responsereply = generate_response(final_model_prompt,search_context=search_context_text,conversation_context=conversation_context)# 9. Update the history: The Gradio Chatbot component handles replacing the temporary None.history[-1][1] = replyreturn history, ""2 unmodified lineswith gr.Blocks(title="OkemoLLM") as demo:gr.Markdown("# OkemoLLM (English-only, Online Learning & Web Search Enabled with 1-Turn Context)")chat = gr.Chatbot(height=500)with gr.Row():with gr.Column(scale=4):# The Textbox that the user types intomsg = gr.Textbox(placeholder="Type your message…", label="Message", elem_id="okemo-input-textbox")# Hidden state components for the JS front-end to communicate state# The elem_id is critical for the external JS to find these elements.uploaded_file_state = gr.File(label="Uploaded File", visible=False, elem_id="uploaded_file_state")web_search_enabled_state = gr.Checkbox(label="Web Search Toggle", visible=False, elem_id="web_search_enabled_state")clear = gr.Button("Clear")# NEW: Hidden button that the JavaScript will "click" to trigger the full submission chainsend_trigger = gr.Button(visible=False, elem_id="okemo-send-button-trigger")def add_user_message_to_history(message, history, file_ref, web_enabled):# This function updates the history to show the user message (with a temporary None for response)if file_ref:# Append filename for history visibilitymessage = f"{message} (Attached: {file_ref.name.split('/')[-1]})"return history + [[message, None]]# Chain of events for SUBMISSION (triggered by Textbox Enter or the hidden Button):# 1. Textbox Enter eventmsg.submit(add_user_message_to_history,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, msg], # Clear msg textbox after first stepqueue=False).then(on_submit,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat],)# 2. Hidden Button Click event (triggered by JS for the actual Send button)send_trigger.click(add_user_message_to_history,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, msg], # Clear msg textbox after first stepqueue=False).then(on_submit,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat],)# Clear history eventclear.click(lambda: [], None, chat, queue=False)# --- 3. FEEDBACK API ENDPOINTS ---def feedback_good_wrapper(history_state):return process_feedback(history_state, "Good Response")def feedback_bad_wrapper(history_state):return process_feedback(history_state, "Bad Response")gr.Interface(fn=feedback_good_wrapper,inputs=[gr.State(value=[])],outputs=[gr.State(value=[]), gr.Textbox(visible=False)],api_name="feedback_good",live=False,allow_flagging="never",)gr.Interface(fn=feedback_bad_wrapper,inputs=[gr.State(value=[])],outputs=[gr.State(value=[]), gr.Textbox(visible=False)],api_name="feedback_bad",live=False,allow_flagging="never")demo.queue(api_open=True).launch()1234522 unmodified lines282930313233349 unmodified lines444546474849505152535455562 unmodified lines5960616263647 unmodified lines7273747576777879809 unmodified lines909192939495969798991004 unmodified lines1051061071081091101111 unmodified line1131141151161171181191201 unmodified line12212312412512612712812913013113213313413513613713813922 unmodified lines1621631641651661671688 unmodified lines17717817918018118218318418518618720 unmodified lines20820921021121221321421521621721821922022122222322422522622722822931 unmodified lines2612622632642652662678 unmodified lines27627727827928028128219 unmodified lines3023033043053063073087 unmodified lines3163173183193203213223233243253263273283293303313323333343353361 unmodified line33833934034134234334434534634734834935035135235335435535635735835936036136236310 unmodified lines3743753763773783793803818 unmodified lines3903913923933943953963973983994004014024034042 unmodified lines407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486# app.pyimport osimport mathimport re22 unmodified linesself.word2index = {self.PAD: 0, self.SOS: 1, self.EOS: 2, self.UNK: 3, self.SYSTEM: 4}self.index2word = {0: self.PAD, 1: self.SOS, 2: self.EOS, 3: self.UNK, 4: self.SYSTEM}self.n_words = 5@staticmethoddef load_from_checkpoint(checkpoint):voc = Voc()9 unmodified linesvoc.SYSTEM = tokens.get("SYSTEM", "<SYSTEM>")return voc# English-only sanitation:_WORD_TOKEN_CHARS = r"a-z0-9\'\-"_SPLIT_PUNCT = r"\.\,\!\?\:\;\(\)\[\]\{\}\"\/\\@#\$%\^&\*\+\<>=~`"_token_re = re.compile(rf"[{_WORD_TOKEN_CHARS}]+|[{_SPLIT_PUNCT}]", flags=re.IGNORECASE)def to_ascii(text: str) -> str:text = unicodedata.normalize("NFKC", text)return text.encode("ascii", errors="ignore").decode("ascii")2 unmodified linesreturn _token_re.findall(ascii_text)def is_english_like(text: str, min_alpha_ratio: float = 0.6, max_non_ascii: int = 0):norm = unicodedata.normalize("NFKC", text)non_ascii_count = sum(1 for ch in norm if ord(ch) > 127)if non_ascii_count > max_non_ascii:7 unmodified linesreturn ratio >= min_alpha_ratiodef check_repetition(text: str, max_repeat: int = 2):tokens = tokenize(text)if not tokens:return Falsefor i in range(len(tokens) - max_repeat):if all(tokens[i] == tokens[j] for j in range(i, i + max_repeat + 1)):return True9 unmodified linespe[:, 0::2] = torch.sin(position * div_term)pe[:, 1::2] = torch.cos(position * div_term)self.register_buffer("pe", pe.unsqueeze(0))def forward(self, x):return x + self.pe[:, : x.size(1), :]class GPT(nn.Module):def __init__(self, n_words, d_model, n_layers, n_head, d_ff, dropout=0.1):super().__init__()4 unmodified linesself.transformer = nn.TransformerEncoder(enc_layer, n_layers)self.fc = nn.Linear(d_model, n_words, bias=False)self.fc.weight = self.embedding.weightdef forward(self, x, mask=None, key_padding_mask=None):x = self.embedding(x)x = self.pos(x)1 unmodified lineout = self.transformer(x, mask=mask, src_key_padding_mask=key_padding_mask)return self.fc(out)def indexes_from_sentence(voc, sentence):sanitized = " ".join(tokenize(sentence))prompt_tokens = [voc.SYSTEM] + tokenize(sanitized)return [voc.word2index.get(tok, voc.word2index[voc.UNK]) for tok in prompt_tokens] + [voc.word2index[voc.EOS]]1 unmodified linedef make_bool_causal_mask(sz, device):return torch.triu(torch.ones((sz, sz), dtype=torch.bool, device=device), diagonal=1)device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")CHECKPOINT_PATH = "checkpoint.pth"if not os.path.exists(CHECKPOINT_PATH):print("WARNING: Using dummy checkpoint as real file not found. Online learning will not affect model state permanently.")checkpoint = {"voc_word2index": Voc().word2index,"voc_index2word": Voc().index2word,"gpt_model_state_dict": None}d_model = 768n_head = 48d_ff = 76822 unmodified linesgpt_model = GPT(voc.n_words, d_model, n_layers, n_head, d_ff, dropout).to(device)if "gpt_model_state_dict" in checkpoint and checkpoint["gpt_model_state_dict"] is not None:gpt_model.load_state_dict(checkpoint["gpt_model_state_dict"], strict=True)optimizer = optim.Adam(gpt_model.parameters(), lr=LEARNING_RATE)criterion = nn.CrossEntropyLoss(ignore_index=voc.word2index[voc.PAD])8 unmodified lineselse:return ""def online_update(model, input_sentence, target_response, max_seq_len, search_context="", conversation_context=""):is_response_clean = is_english_like(target_response, min_alpha_ratio=0.7) and not any(t in target_response for t in [voc.UNK, "i couldn't generate"])is_not_repetitive = not check_repetition(target_response, max_repeat=2)if not is_response_clean or not is_not_repetitive:print("Skipping online update: Target response is non-English, corrupted, or highly repetitive.")return20 unmodified linestarget_tensor = torch.tensor(target_ids, dtype=torch.long, device=device)L = input_tensor.size(1)model.train()causal = make_bool_causal_mask(L, device)last_loss = 0.0for epoch in range(ONLINE_LEARNING_EPOCHS):optimizer.zero_grad()logits = model(input_tensor, mask=causal, key_padding_mask=None)loss = criterion(logits.squeeze(0), target_tensor)loss.backward()optimizer.step()last_loss = loss.item()model.eval()print(f"Online update performed over {ONLINE_LEARNING_EPOCHS} epochs. Final Loss: {last_loss:.4f}")def generate_response(prompt, search_context="", conversation_context=""):if not is_english_like(prompt):return "Please use English. Non-English input was detected."31 unmodified linescandidate_word = voc.index2word.get(candidate_id, voc.UNK)token_ok = is_english_like(candidate_word, min_alpha_ratio=0.1, max_non_ascii=0)if candidate_id == voc.word2index[voc.EOS]:next_id = candidate_idbreak8 unmodified linesif next_id == voc.word2index[voc.EOS]:breakgenerated.append(next_id)input_tensor = torch.cat([input_tensor, torch.tensor([[next_id]], device=device, dtype=torch.long)],19 unmodified linesreturn history, "Cannot process feedback: No recent AI response found."last_user_message, last_ai_response = history[-1][0], history[-1][1]print(f"\n--- FEEDBACK RECEIVED ---")print(f"Rating: {rating}")print(f"User Prompt: '{last_user_message}'")7 unmodified linesconversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"online_update(gpt_model,last_user_message,last_ai_response,max_length,search_context="",conversation_context=conversation_context)feedback_message = f"Thanks for the **Good Response** rating! I just learned from that. Keep the good prompts coming! ✨"elif rating == "Bad Response":feedback_message = f"Acknowledged **Bad Response** feedback. I will try to be better! 🛠"else:feedback_message = "Unknown rating received."return history, feedback_message1 unmodified line"""The central handler called by the front-end when the user submits a message."""# Defensive: ensure history has a pending assistant slotif history is None:history = []if len(history) == 0 or history[-1][1] is not None:history.append([user_message, None])# 1. Handle file upload (Placeholder)file_context = ""if uploaded_file:file_name = uploaded_file.name.split("/")[-1]file_context = f"The user has provided a file named '{file_name}'. Analyze or respond to the user's prompt *about this file*."print(f"File attached: {file_name}")# 2. Determine if this is a regeneration/enhancement instructionis_instruction = any(user_message.lower().startswith(p) for p in ["please generate", "provide a much more detailed", "provide a different"])# 3. Extract the clean message for the model inputmatch = re.search(r':\s*"(.+?)"$', user_message)if is_instruction and match:clean_user_message = match.group(1).strip()model_prompt = user_message10 unmodified linesconversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"print(f"Context included: {conversation_context}")# 5. Enforce English-only input for the *clean* messageif not is_english_like(clean_user_message):history[-1][1] = "Please use English. Non-English input was detected."return history, ""8 unmodified lines# 7. Prepend file context (if any) to the model's promptfinal_model_prompt = f"{file_context} {model_prompt}" if file_context else model_prompt# 8. Generate responsereply = generate_response(final_model_prompt,search_context=search_context_text,conversation_context=conversation_context)# 9. Update the historyhistory[-1][1] = replyreturn history, ""2 unmodified lineswith gr.Blocks(title="OkemoLLM") as demo:gr.Markdown("# OkemoLLM (English-only, Online Learning & Web Search Enabled with 1-Turn Context)")chat = gr.Chatbot(height=500)with gr.Row():with gr.Column(scale=4):msg = gr.Textbox(placeholder="Type your message…", label="Message", elem_id="okemo-input-textbox")uploaded_file_state = gr.File(label="Uploaded File", visible=False, elem_id="uploaded_file_state")web_search_enabled_state = gr.Checkbox(label="Web Search Toggle", visible=False, elem_id="web_search_enabled_state")clear = gr.Button("Clear")send_trigger = gr.Button(visible=False, elem_id="okemo-send-button-trigger")def add_user_message_to_history(message, history, file_ref, web_enabled):"""Returns:- updated chat history (for the Chatbot)- empty string to clear the Textbox"""if file_ref:message = f"{message} (Attached: {file_ref.name.split('/')[-1]})"updated_history = (history or []) + [[message, None]]return updated_history, "" # Chatbot history, cleared textbox# 1. Textbox Enter eventmsg.submit(add_user_message_to_history,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, msg], # two outputs expectedqueue=False).then(on_submit,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat],)# 2. Hidden Button Click eventsend_trigger.click(add_user_message_to_history,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat, msg], # two outputs expectedqueue=False).then(on_submit,[msg, chat, uploaded_file_state, web_search_enabled_state],[chat],)# Clear history eventclear.click(lambda: [], None, chat, queue=False)# --- 3. FEEDBACK API ENDPOINTS ---def feedback_good_wrapper(history_state):return process_feedback(history_state, "Good Response")def feedback_bad_wrapper(history_state):return process_feedback(history_state, "Bad Response")gr.Interface(fn=feedback_good_wrapper,inputs=[gr.State(value=[])],outputs=[gr.State(value=[]), gr.Textbox(visible=False)],api_name="feedback_good",live=False,allow_flagging="never",)gr.Interface(fn=feedback_bad_wrapper,inputs=[gr.State(value=[])],outputs=[gr.State(value=[]), gr.Textbox(visible=False)],api_name="feedback_bad",live=False,allow_flagging="never")# Enable SSR info message and make public link configurabledemo.queue(api_open=True).launch()
app.py+76-86