Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435361 unmodified line38394041424344454647484950515253545556575859601 unmodified line6263646566679 unmodified lines777879808182838485868788899091922 unmodified lines959697989910010110210310410510610710810911015 unmodified lines1261271281291301311321332 unmodified lines1361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661673 unmodified lines17117217317417517617732 unmodified lines2102112122132142152162 unmodified lines21922022122222322422512 unmodified lines23823924024124224324424524624724824925011 unmodified lines26226326426526626726826927027127227327412 unmodified lines2872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223232 unmodified lines32632732832933033133233333433533633733833934034134234334434534634734834935035135235335429 unmodified lines3843853863873883893903913923931 unmodified line3953963973983994005 unmodified lines4064074084094104114122 unmodified lines4154164174184194204214224234244254264274285 unmodified lines4344354364374384394403 unmodified lines4444454464474484494504514524532 unmodified lines4564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934943 unmodified lines49849950050150250350419 unmodified lines524525526527528529530531532533534import gradio as grimport torchimport torch.nn.functional as Ffrom transformers import AutoTokenizer, AutoModelForCausalLM, AutoModelForMaskedLMimport numpy as npimport pandas as pdimport spacyfrom spacy import displacyimport mathimport warningstry:from config import DEFAULT_MODELS, MODEL_SETTINGS, VIZ_SETTINGS, PROCESSING_SETTINGS, UI_SETTINGS, ERROR_MESSAGESexcept ImportError:# Fallback configuration if config.py is not availableDEFAULT_MODELS = {"decoder": ["gpt2", "distilgpt2"],"encoder": ["bert-base-uncased", "distilbert-base-uncased"]}MODEL_SETTINGS = {"max_length": 512}VIZ_SETTINGS = {"max_perplexity_display": 50.0,"color_scheme": {"low_perplexity": {"r": 46, "g": 204, "b": 113},"medium_perplexity": {"r": 241, "g": 196, "b": 15},"high_perplexity": {"r": 231, "g": 76, "b": 60},"background_alpha": 0.7,"border_alpha": 0.9},"thresholds": {"low_threshold": 0.3,"high_threshold": 0.7},"displacy_options": {"ents": ["PP"], "colors": {}}}PROCESSING_SETTINGS = {"epsilon": 1e-10,1 unmodified line"min_mask_probability": 0.05,"max_mask_probability": 0.5,"default_min_samples": 10,"min_samples_range": (5, 50)}UI_SETTINGS = {"title": "π Perplexity Viewer","description": "Visualize per-token perplexity using color gradients.","examples": [{"text": "The quick brown fox jumps over the lazy dog.", "model": "gpt2", "type": "decoder", "mask_prob": 0.15, "min_samples": 10},{"text": "The capital of France is Paris.", "model": "bert-base-uncased", "type": "encoder", "mask_prob": 0.15, "min_samples": 10},{"text": "Quantum entanglement defies classical physics intuition completely.", "model": "distilgpt2", "type": "decoder", "mask_prob": 0.15, "min_samples": 10},{"text": "Machine learning requires large datasets for training.", "model": "distilbert-base-uncased", "type": "encoder", "mask_prob": 0.2, "min_samples": 15},{"text": "Artificial intelligence transforms modern computing paradigms.", "model": "bert-base-uncased", "type": "encoder", "mask_prob": 0.1, "min_samples": 20}]}ERROR_MESSAGES = {"empty_text": "Please enter some text to analyze.","model_load_error": "Error loading model {model_name}: {error}","processing_error": "Error processing text: {error}"}warnings.filterwarnings("ignore")1 unmodified linecached_models = {}cached_tokenizers = {}def load_model_and_tokenizer(model_name, model_type):"""Load and cache model and tokenizer"""cache_key = f"{model_name}_{model_type}"9 unmodified linesif model_type == "decoder":model = AutoModelForCausalLM.from_pretrained(model_name,torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,device_map="auto" if torch.cuda.is_available() else None,trust_remote_code=True)else: # encodermodel = AutoModelForMaskedLM.from_pretrained(model_name,torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,device_map="auto" if torch.cuda.is_available() else None,trust_remote_code=True)model.eval() # Set to evaluation mode2 unmodified linesreturn model, tokenizerexcept Exception as e:raise gr.Error(ERROR_MESSAGES["model_load_error"].format(model_name=model_name, error=str(e)))return cached_models[cache_key], cached_tokenizers[cache_key]def calculate_decoder_perplexity(text, model, tokenizer):"""Calculate perplexity for decoder models (like GPT)"""device = next(model.parameters()).device# Tokenize the textinputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=MODEL_SETTINGS["max_length"])input_ids = inputs.input_ids.to(device)if input_ids.size(1) < 2:15 unmodified linesshift_labels = input_ids[..., 1:].contiguous()# Calculate per-token lossesloss_fct = torch.nn.CrossEntropyLoss(reduction='none')token_losses = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))token_perplexities = torch.exp(token_losses).cpu().numpy()# Get tokens (excluding the first one since we predict next tokens)2 unmodified lines# Clean up tokens for displaycleaned_tokens = []for token in tokens:if token.startswith('Δ '):cleaned_tokens.append(token[1:]) # Remove Δ prefixelif token.startswith('##'):cleaned_tokens.append(token[2:]) # Remove ## prefixelse:cleaned_tokens.append(token)return perplexity, cleaned_tokens, token_perplexitiesdef calculate_encoder_perplexity(text, model, tokenizer, mask_probability=0.15, min_samples_per_token=10):"""Calculate pseudo-perplexity for encoder models using statistical sampling with multiple token masking"""device = next(model.parameters()).device# Tokenize the textinputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=MODEL_SETTINGS["max_length"])input_ids = inputs.input_ids.to(device)if input_ids.size(1) < 3: # Need at least [CLS] + 1 token + [SEP]raise gr.Error("Text is too short for MLM perplexity calculation.")seq_length = input_ids.size(1)special_token_ids = {tokenizer.cls_token_id, tokenizer.sep_token_id, tokenizer.pad_token_id}# Get content token indices (excluding special tokens)content_token_indices = [i for i in range(seq_length)if input_ids[0, i].item() not in special_token_ids]if not content_token_indices:raise gr.Error("No content tokens found for analysis.")3 unmodified lines# Calculate overall average perplexity and collect samplesall_losses = []max_iterations = min_samples_per_token * 50 # Safety limit to prevent infinite loopsiteration = 0with torch.no_grad():32 unmodified linesiteration += 1# Check if we have enough samples for all tokensmin_samples_collected = min(len(samples) for samples in token_perplexity_samples.values())if min_samples_collected >= min_samples_per_token:break2 unmodified linesavg_loss = np.mean(all_losses)overall_perplexity = math.exp(avg_loss)else:overall_perplexity = float('inf')# Calculate mean perplexity per token for visualizationtokens = tokenizer.convert_ids_to_tokens(input_ids[0])12 unmodified lines# Clean up tokens for displaycleaned_tokens = []for token in tokens:if token.startswith('##'):cleaned_tokens.append(token[2:])else:cleaned_tokens.append(token)return overall_perplexity, cleaned_tokens, np.array(token_perplexities)def create_visualization(tokens, perplexities):"""Create custom HTML visualization with color-coded perplexities"""if len(tokens) == 0:11 unmodified lines'<h3 style="margin-top: 0; color: #333;">Per-token Perplexity Visualization</h3>','<div style="margin-bottom: 15px;">','<span style="font-size: 12px; color: #666;">','π’ Low perplexity (confident) β π‘ Medium β π΄ High perplexity (uncertain)','</span>','</div>','<div style="line-height: 2.0;">']for i, (token, perp, norm_perp) in enumerate(zip(tokens, perplexities, normalized_perplexities)):# Skip empty tokensif not token.strip():continue12 unmodified lineshigh_thresh = VIZ_SETTINGS.get("thresholds", {}).get("high_threshold", 0.7)# Get colors from configurationlow_color = VIZ_SETTINGS["color_scheme"]["low_perplexity"]med_color = VIZ_SETTINGS["color_scheme"]["medium_perplexity"]high_color = VIZ_SETTINGS["color_scheme"]["high_perplexity"]# Map perplexity to color using configurationif norm_perp < low_thresh: # Low perplexity - green# Interpolate between green and yellowfactor = norm_perp / low_threshred = int(low_color["r"] + factor * (med_color["r"] - low_color["r"]))green = int(low_color["g"] + factor * (med_color["g"] - low_color["g"]))blue = int(low_color["b"] + factor * (med_color["b"] - low_color["b"]))elif norm_perp < high_thresh: # Medium perplexity - yellow/orange# Interpolate between yellow and redfactor = (norm_perp - low_thresh) / (high_thresh - low_thresh)red = int(med_color["r"] + factor * (high_color["r"] - med_color["r"]))green = int(med_color["g"] + factor * (high_color["g"] - med_color["g"]))blue = int(med_color["b"] + factor * (high_color["b"] - med_color["b"]))else: # High perplexity - red# Use high perplexity color, potentially darker for very high valuesfactor = min((norm_perp - high_thresh) / (1.0 - high_thresh), 1.0)darken = 0.8 - (factor * 0.3) # Darken by up to 30%red = int(high_color["r"] * darken)green = int(high_color["g"] * darken)blue = int(high_color["b"] * darken)tooltip_text = f"Perplexity: {perp:.3f} (normalized: {norm_perp:.3f})"# Clamp valuesred = max(0, min(255, red))green = max(0, min(255, green))blue = max(0, min(255, blue))# Get alpha values from configurationbg_alpha = VIZ_SETTINGS["color_scheme"].get("background_alpha", 0.7)2 unmodified lines# Create colored span with tooltiphtml_parts.append(f'<span style="'f'background-color: rgba({red}, {green}, {blue}, {bg_alpha}); 'f'color: #000; 'f'padding: 2px 4px; 'f'margin: 1px; 'f'border-radius: 3px; 'f'border: 1px solid rgba({red}, {green}, {blue}, {border_alpha}); 'f'font-weight: 500; 'f'cursor: help; 'f'display: inline-block;'f'" title="{tooltip_text}">{clean_token}</span>')html_parts.extend(['</div>','<div style="margin-top: 15px; font-size: 12px; color: #666;">',f'Max perplexity in visualization: {max_perplexity:.2f} | ',f'Total tokens: {len(tokens)}','</div>','</div>'])return "".join(html_parts)def process_text(text, model_name, model_type, mask_probability=0.15, min_samples=10):"""Main processing function"""if not text.strip():29 unmodified lines{sampling_info}"""# Create detailed results tabledf = pd.DataFrame({'Token': tokens,'Perplexity': [f"{p:.4f}" for p in token_perplexities]})return summary, viz_html, df1 unmodified lineerror_msg = ERROR_MESSAGES["processing_error"].format(error=str(e))return error_msg, "", pd.DataFrame()# Create Gradio interfacewith gr.Blocks(title=UI_SETTINGS["title"], theme=gr.themes.Soft()) as demo:gr.Markdown(f"# {UI_SETTINGS['title']}")5 unmodified lineslabel="Input Text",placeholder="Enter the text you want to analyze...",lines=6,max_lines=10)with gr.Row():2 unmodified lineschoices=DEFAULT_MODELS["decoder"] + DEFAULT_MODELS["encoder"],value="gpt2",allow_custom_value=True,info="Select a model or enter a custom HuggingFace model name")model_type = gr.Radio(label="Model Type",choices=["decoder", "encoder"],value="decoder",info="Decoder for causal LM, Encoder for masked LM")# Advanced settings for encoder models5 unmodified linesvalue=PROCESSING_SETTINGS["default_mask_probability"],step=0.05,visible=False,info="Probability of masking each token per iteration (encoder only)")min_samples = gr.Slider(3 unmodified linesvalue=PROCESSING_SETTINGS["default_min_samples"],step=5,visible=False,info="Minimum perplexity samples to collect per token (encoder only)")analyze_btn = gr.Button("π Analyze Perplexity", variant="primary", size="lg")with gr.Column(scale=3):summary_output = gr.Markdown(label="Summary")2 unmodified lines# Full-width tablewith gr.Row():table_output = gr.Dataframe(label="Detailed Token Results",interactive=False,wrap=True)# Update model dropdown based on type selectiondef update_model_choices(model_type):return gr.update(choices=DEFAULT_MODELS[model_type], value=DEFAULT_MODELS[model_type][0])def toggle_advanced_settings(model_type):is_encoder = (model_type == "encoder")return [gr.update(visible=is_encoder), # mask_probabilitygr.update(visible=is_encoder) # min_samples]model_type.change(fn=lambda mt: [update_model_choices(mt)] + toggle_advanced_settings(mt),inputs=[model_type],outputs=[model_name, mask_probability, min_samples])# Set up the analysis functionanalyze_btn.click(fn=process_text,inputs=[text_input, model_name, model_type, mask_probability, min_samples],outputs=[summary_output, viz_output, table_output])# Add exampleswith gr.Accordion("π Example Texts", open=False):examples_data = [[ex["text"], ex["model"], ex["type"], ex.get("mask_prob", 0.15), ex.get("min_samples", 10)]for ex in UI_SETTINGS["examples"]]3 unmodified linesoutputs=[summary_output, viz_output, table_output],fn=process_text,cache_examples=False,label="Click on an example to try it out:")# Add footer with information19 unmodified linesif __name__ == "__main__":try:demo.launch(server_name="0.0.0.0",server_port=7860,show_api=False)except Exception as e:print(f"β Failed to launch app: {e}")print("π‘ Try running with: python run.py")123456789101112131415161718192021222324252627282930313233343536373839401 unmodified line42434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293941 unmodified line969798991001011029 unmodified lines1121131141151161171181191201211221231241251261271281291301312 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715815915 unmodified lines1751761771781791801811821831842 unmodified lines1871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302313 unmodified lines23523623723823924024124224332 unmodified lines2762772782792802812822832842 unmodified lines28728828929029129229312 unmodified lines30630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336411 unmodified lines37637737837938038138238338438538638738838939012 unmodified lines4034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384392 unmodified lines44244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247329 unmodified lines5035045055065075085095105111 unmodified line5135145155165175185195 unmodified lines5255265275285295305312 unmodified lines5345355365375385395405415425435445455465475 unmodified lines5535545555565575585593 unmodified lines5635645655665675685695705715725735742 unmodified lines5775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206213 unmodified lines62562662762862963063119 unmodified lines651652653654655656657import mathimport warningsimport gradio as grimport numpy as npimport pandas as pdimport torchimport torch.nn.functional as Ffrom transformers import AutoModelForCausalLM, AutoModelForMaskedLM, AutoTokenizertry:from config import (DEFAULT_MODELS,ERROR_MESSAGES,MODEL_SETTINGS,PROCESSING_SETTINGS,UI_SETTINGS,VIZ_SETTINGS,)except ImportError:# Fallback configuration if config.py is not availableDEFAULT_MODELS = {"decoder": ["gpt2", "distilgpt2"],"encoder": ["bert-base-uncased", "distilbert-base-uncased"],}MODEL_SETTINGS = {"max_length": 512}VIZ_SETTINGS = {"max_perplexity_display": 1000.0,"color_scheme": {"low_perplexity": {"r": 46, "g": 204, "b": 113},"medium_perplexity": {"r": 241, "g": 196, "b": 15},"high_perplexity": {"r": 231, "g": 76, "b": 60},"background_alpha": 0.7,"border_alpha": 0.9,},"thresholds": {"low_threshold": 0.3, "high_threshold": 0.7},"displacy_options": {"ents": ["PP"], "colors": {}},}PROCESSING_SETTINGS = {"epsilon": 1e-10,1 unmodified line"min_mask_probability": 0.05,"max_mask_probability": 0.5,"default_min_samples": 10,"min_samples_range": (5, 50),}UI_SETTINGS = {"title": "π Perplexity Viewer","description": "Visualize per-token perplexity using color gradients.","examples": [{"text": "The quick brown fox jumps over the lazy dog.","model": "gpt2","type": "decoder","mask_prob": 0.15,"min_samples": 10,},{"text": "The capital of France is Paris.","model": "bert-base-uncased","type": "encoder","mask_prob": 0.15,"min_samples": 10,},{"text": "Quantum entanglement defies classical physics intuition completely.","model": "distilgpt2","type": "decoder","mask_prob": 0.15,"min_samples": 10,},{"text": "Machine learning requires large datasets for training.","model": "distilbert-base-uncased","type": "encoder","mask_prob": 0.2,"min_samples": 15,},{"text": "Artificial intelligence transforms modern computing paradigms.","model": "bert-base-uncased","type": "encoder","mask_prob": 0.1,"min_samples": 20,},],}ERROR_MESSAGES = {"empty_text": "Please enter some text to analyze.","model_load_error": "Error loading model {model_name}: {error}","processing_error": "Error processing text: {error}",}warnings.filterwarnings("ignore")1 unmodified linecached_models = {}cached_tokenizers = {}def load_model_and_tokenizer(model_name, model_type):"""Load and cache model and tokenizer"""cache_key = f"{model_name}_{model_type}"9 unmodified linesif model_type == "decoder":model = AutoModelForCausalLM.from_pretrained(model_name,torch_dtype=torch.float16if torch.cuda.is_available()else torch.float32,device_map="auto" if torch.cuda.is_available() else None,trust_remote_code=True,)else: # encodermodel = AutoModelForMaskedLM.from_pretrained(model_name,torch_dtype=torch.float16if torch.cuda.is_available()else torch.float32,device_map="auto" if torch.cuda.is_available() else None,trust_remote_code=True,)model.eval() # Set to evaluation mode2 unmodified linesreturn model, tokenizerexcept Exception as e:raise gr.Error(ERROR_MESSAGES["model_load_error"].format(model_name=model_name, error=str(e)))return cached_models[cache_key], cached_tokenizers[cache_key]def calculate_decoder_perplexity(text, model, tokenizer):"""Calculate perplexity for decoder models (like GPT)"""device = next(model.parameters()).device# Tokenize the textinputs = tokenizer(text,return_tensors="pt",truncation=True,max_length=MODEL_SETTINGS["max_length"],)input_ids = inputs.input_ids.to(device)if input_ids.size(1) < 2:15 unmodified linesshift_labels = input_ids[..., 1:].contiguous()# Calculate per-token lossesloss_fct = torch.nn.CrossEntropyLoss(reduction="none")token_losses = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))token_perplexities = torch.exp(token_losses).cpu().numpy()# Get tokens (excluding the first one since we predict next tokens)2 unmodified lines# Clean up tokens for displaycleaned_tokens = []for token in tokens:if token.startswith("Δ "):cleaned_tokens.append(token[1:]) # Remove Δ prefixelif token.startswith("##"):cleaned_tokens.append(token[2:]) # Remove ## prefixelse:cleaned_tokens.append(token)return perplexity, cleaned_tokens, token_perplexitiesdef calculate_encoder_perplexity(text, model, tokenizer, mask_probability=0.15, min_samples_per_token=10):"""Calculate pseudo-perplexity for encoder models using statistical sampling with multiple token masking"""device = next(model.parameters()).device# Tokenize the textinputs = tokenizer(text,return_tensors="pt",truncation=True,max_length=MODEL_SETTINGS["max_length"],)input_ids = inputs.input_ids.to(device)if input_ids.size(1) < 3: # Need at least [CLS] + 1 token + [SEP]raise gr.Error("Text is too short for MLM perplexity calculation.")seq_length = input_ids.size(1)special_token_ids = {tokenizer.cls_token_id,tokenizer.sep_token_id,tokenizer.pad_token_id,}# Get content token indices (excluding special tokens)content_token_indices = [i for i in range(seq_length) if input_ids[0, i].item() not in special_token_ids]if not content_token_indices:raise gr.Error("No content tokens found for analysis.")3 unmodified lines# Calculate overall average perplexity and collect samplesall_losses = []max_iterations = (min_samples_per_token * 50) # Safety limit to prevent infinite loopsiteration = 0with torch.no_grad():32 unmodified linesiteration += 1# Check if we have enough samples for all tokensmin_samples_collected = min(len(samples) for samples in token_perplexity_samples.values())if min_samples_collected >= min_samples_per_token:break2 unmodified linesavg_loss = np.mean(all_losses)overall_perplexity = math.exp(avg_loss)else:overall_perplexity = float("inf")# Calculate mean perplexity per token for visualizationtokens = tokenizer.convert_ids_to_tokens(input_ids[0])12 unmodified lines# Clean up tokens for displaycleaned_tokens = []for token in tokens:if token.startswith("##"):cleaned_tokens.append(token[2:])else:cleaned_tokens.append(token)return overall_perplexity, cleaned_tokens, np.array(token_perplexities)def perplexity_to_color(perplexity, min_perp=1, max_perp=1000):"""Convert perplexity to a color on a gradient from green to red.Uses logarithmic scale for better visual distribution.Args:perplexity: The perplexity valuemin_perp: Minimum perplexity (maps to green)max_perp: Maximum perplexity (maps to red)Returns:Hex color string (e.g., "#00FF00")"""# Clamp perplexity to rangeperp = max(min_perp, min(max_perp, perplexity))# Use logarithmic scale for better distributionlog_min = math.log(min_perp)log_max = math.log(max_perp)log_perp = math.log(perp)# Normalize to 0-1 rangenormalized = (log_perp - log_min) / (log_max - log_min)# Create color gradient from green to red via yellow# Green: (0, 178, 0) - HSL(120, 100%, 35%)# Yellow: (255, 255, 0) - HSL(60, 100%, 50%)# Red: (255, 0, 0) - HSL(0, 100%, 50%)if normalized < 0.5:# Green to Yellowfactor = normalized * 2 # 0 to 1r = int(0 + factor * 255)g = int(178 + factor * (255 - 178))b = 0else:# Yellow to Redfactor = (normalized - 0.5) * 2 # 0 to 1r = 255g = int(255 * (1 - factor))b = 0return f"#{r:02x}{g:02x}{b:02x}"def create_visualization(tokens, perplexities):"""Create custom HTML visualization with color-coded perplexities"""if len(tokens) == 0:11 unmodified lines'<h3 style="margin-top: 0; color: #333;">Per-token Perplexity Visualization</h3>','<div style="margin-bottom: 15px;">','<span style="font-size: 12px; color: #666;">',"π’ Low perplexity (confident) β π‘ Medium β π΄ High perplexity (uncertain)","</span>","</div>",'<div style="line-height: 2.0;">',]for i, (token, perp, norm_perp) in enumerate(zip(tokens, perplexities, normalized_perplexities)):# Skip empty tokensif not token.strip():continue12 unmodified lineshigh_thresh = VIZ_SETTINGS.get("thresholds", {}).get("high_threshold", 0.7)# Get colors from configuration# low_color = VIZ_SETTINGS["color_scheme"]["low_perplexity"]# med_color = VIZ_SETTINGS["color_scheme"]["medium_perplexity"]# high_color = VIZ_SETTINGS["color_scheme"]["high_perplexity"]# # Map perplexity to color using configuration# if norm_perp < low_thresh: # Low perplexity - green# # Interpolate between green and yellow# factor = norm_perp / low_thresh# red = int(low_color["r"] + factor * (med_color["r"] - low_color["r"]))# green = int(low_color["g"] + factor * (med_color["g"] - low_color["g"]))# blue = int(low_color["b"] + factor * (med_color["b"] - low_color["b"]))# elif norm_perp < high_thresh: # Medium perplexity - yellow/orange# # Interpolate between yellow and red# factor = (norm_perp - low_thresh) / (high_thresh - low_thresh)# red = int(med_color["r"] + factor * (high_color["r"] - med_color["r"]))# green = int(med_color["g"] + factor * (high_color["g"] - med_color["g"]))# blue = int(med_color["b"] + factor * (high_color["b"] - med_color["b"]))# else: # High perplexity - red# # Use high perplexity color, potentially darker for very high values# factor = min((norm_perp - high_thresh) / (1.0 - high_thresh), 1.0)# darken = 0.8 - (factor * 0.3) # Darken by up to 30%# red = int(high_color["r"] * darken)# green = int(high_color["g"] * darken)# blue = int(high_color["b"] * darken)tooltip_text = f"Perplexity: {perp:.3f} (normalized: {norm_perp:.3f})"# Clamp values# red = max(0, min(255, red))# green = max(0, min(255, green))# blue = max(0, min(255, blue))# Get alpha values from configurationbg_alpha = VIZ_SETTINGS["color_scheme"].get("background_alpha", 0.7)2 unmodified lines# Create colored span with tooltiphtml_parts.append(f'<span style="'f"background-color: rgba({perplexity_to_color(perp, min_perp=1, max_perp=VIZ_SETTINGS['max_perplexity_display'])}, {bg_alpha}); "f"color: #000; "f"padding: 2px 4px; "f"margin: 1px; "f"border-radius: 3px; "f"border: 1px solid rgba({perplexity_to_color(perp, min_perp=1, max_perp=VIZ_SETTINGS['max_perplexity_display'])}, {border_alpha}); "f"font-weight: 500; "f"cursor: help; "f"display: inline-block;"f'" title="{tooltip_text}">{clean_token}</span>')html_parts.extend(["</div>",'<div style="margin-top: 15px; font-size: 12px; color: #666;">',f"Max perplexity in visualization: {max_perplexity:.2f} | ",f"Total tokens: {len(tokens)}","</div>","</div>",])return "".join(html_parts)def process_text(text, model_name, model_type, mask_probability=0.15, min_samples=10):"""Main processing function"""if not text.strip():29 unmodified lines{sampling_info}"""# Create detailed results tabledf = pd.DataFrame({"Token": tokens, "Perplexity": [f"{p:.4f}" for p in token_perplexities]})return summary, viz_html, df1 unmodified lineerror_msg = ERROR_MESSAGES["processing_error"].format(error=str(e))return error_msg, "", pd.DataFrame()# Create Gradio interfacewith gr.Blocks(title=UI_SETTINGS["title"], theme=gr.themes.Soft()) as demo:gr.Markdown(f"# {UI_SETTINGS['title']}")5 unmodified lineslabel="Input Text",placeholder="Enter the text you want to analyze...",lines=6,max_lines=10,)with gr.Row():2 unmodified lineschoices=DEFAULT_MODELS["decoder"] + DEFAULT_MODELS["encoder"],value="gpt2",allow_custom_value=True,info="Select a model or enter a custom HuggingFace model name",)model_type = gr.Radio(label="Model Type",choices=["decoder", "encoder"],value="decoder",info="Decoder for causal LM, Encoder for masked LM",)# Advanced settings for encoder models5 unmodified linesvalue=PROCESSING_SETTINGS["default_mask_probability"],step=0.05,visible=False,info="Probability of masking each token per iteration (encoder only)",)min_samples = gr.Slider(3 unmodified linesvalue=PROCESSING_SETTINGS["default_min_samples"],step=5,visible=False,info="Minimum perplexity samples to collect per token (encoder only)",)analyze_btn = gr.Button("π Analyze Perplexity", variant="primary", size="lg")with gr.Column(scale=3):summary_output = gr.Markdown(label="Summary")2 unmodified lines# Full-width tablewith gr.Row():table_output = gr.Dataframe(label="Detailed Token Results", interactive=False, wrap=True)# Update model dropdown based on type selectiondef update_model_choices(model_type):return gr.update(choices=DEFAULT_MODELS[model_type], value=DEFAULT_MODELS[model_type][0])def toggle_advanced_settings(model_type):is_encoder = model_type == "encoder"return [gr.update(visible=is_encoder), # mask_probabilitygr.update(visible=is_encoder), # min_samples]model_type.change(fn=lambda mt: [update_model_choices(mt)] + toggle_advanced_settings(mt),inputs=[model_type],outputs=[model_name, mask_probability, min_samples],)# Set up the analysis functionanalyze_btn.click(fn=process_text,inputs=[text_input, model_name, model_type, mask_probability, min_samples],outputs=[summary_output, viz_output, table_output],)# Add exampleswith gr.Accordion("π Example Texts", open=False):examples_data = [[ex["text"],ex["model"],ex["type"],ex.get("mask_prob", 0.15),ex.get("min_samples", 10),]for ex in UI_SETTINGS["examples"]]3 unmodified linesoutputs=[summary_output, viz_output, table_output],fn=process_text,cache_examples=False,label="Click on an example to try it out:",)# Add footer with information19 unmodified linesif __name__ == "__main__":try:demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)except Exception as e:print(f"β Failed to launch app: {e}")print("π‘ Try running with: python run.py")
app.py+240-117