Spaces:
Running
Running
Download app.py from optima-co/next_word_predection: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/spaces/optima-co/next_word_predection/resolve/main/app.py
- Command line
-
hf download hf://spaces/optima-co/next_word_predection/app.py
-
curl -L -o app.py https://huggingface.co/spaces/optima-co/next_word_predection/resolve/main/app.py
10.2 kB
| import gradio as gr | |
| import torch | |
| import torch.nn.functional as F | |
| from transformers import AutoTokenizer, AutoModelForCausalLM | |
| # Load model and tokenizer | |
| print("Loading model...") | |
| tokenizer = AutoTokenizer.from_pretrained('gpt2') | |
| model = AutoModelForCausalLM.from_pretrained('gpt2') | |
| model.eval() | |
| print("Model loaded successfully!") | |
| # Global variable to store current predictions | |
| current_predictions = [] | |
| def get_next_word_predictions(text, top_k=5): | |
| """ | |
| Get top-k next word predictions with probabilities | |
| """ | |
| global current_predictions | |
| if not text or not text.strip(): | |
| current_predictions = [] | |
| return create_predictions_html([]), gr.update(choices=[], value=None) | |
| try: | |
| # Tokenize input | |
| inputs = tokenizer(text, return_tensors="pt") | |
| # Get model output | |
| with torch.no_grad(): | |
| outputs = model(**inputs) | |
| logits = outputs.logits | |
| # Get logits for the last token (next token prediction) | |
| next_token_logits = logits[0, -1, :] | |
| # Convert to probabilities | |
| probs = F.softmax(next_token_logits, dim=-1) | |
| # Get top-k predictions | |
| top_probs, top_indices = torch.topk(probs, top_k) | |
| # Decode tokens to words and store predictions | |
| current_predictions = [] | |
| for i in range(top_k): | |
| token_id = top_indices[i].item() | |
| probability = top_probs[i].item() | |
| word = tokenizer.decode([token_id]) | |
| # Clean up the word for display | |
| display_word = word if word.strip() else "[space]" | |
| current_predictions.append({ | |
| 'rank': i + 1, | |
| 'display_word': display_word, | |
| 'probability': probability * 100, | |
| 'raw_word': word # Store original for appending | |
| }) | |
| # Create HTML display | |
| html = create_predictions_html(current_predictions) | |
| # Create radio choices (hidden but functional) | |
| choices = [f"{p['rank']}. {p['display_word']} ({p['probability']:.1f}%)" for p in current_predictions] | |
| return html, gr.update(choices=choices, value=None) | |
| except Exception as e: | |
| current_predictions = [] | |
| error_html = f"<p style='color: #dc3545; padding: 20px;'>Error: {str(e)}</p>" | |
| return error_html, gr.update(choices=[], value=None) | |
| def create_predictions_html(predictions): | |
| """Create beautiful HTML for predictions""" | |
| if not predictions: | |
| return "<p style='color: #888; text-align: center; padding: 20px;'>Enter some text to see predictions...</p>" | |
| html = '<div style="padding: 0 30px;" id="predictions-container">' | |
| for pred in predictions: | |
| choice_value = f"{pred['rank']}. {pred['display_word']} ({pred['probability']:.1f}%)" | |
| rank = pred['rank'] | |
| # Simple onclick that just uses the rank number (much safer!) | |
| onclick_code = f"(function(){{const rank={rank};const c=document.querySelectorAll('input[type=radio]')[rank-1];if(c){{c.checked=true;c.dispatchEvent(new Event('change',{{bubbles:true}}));c.dispatchEvent(new Event('input',{{bubbles:true}}))}}}})();" | |
| html += f''' | |
| <div class="prediction-item" data-rank="{rank}" style=" | |
| display: flex; | |
| align-items: center; | |
| justify-content: space-between; | |
| padding: 14px 20px; | |
| background: #EAF0FD; | |
| border-radius: 8px; | |
| cursor: pointer; | |
| transition: all 0.2s ease; | |
| border: 2px solid transparent; | |
| margin: 8px 0; | |
| " onmouseover="this.style.background='#DAE5FC'; this.style.transform='translateX(3px)';" | |
| onmouseout="this.style.background='#EAF0FD'; this.style.transform='translateX(0)';" | |
| onclick="{onclick_code}"> | |
| <div style="display: flex; align-items: center; gap: 12px;"> | |
| <span style=" | |
| font-weight: 800; | |
| color: #2c3e50; | |
| font-size: 18px; | |
| font-family: system-ui, -apple-system, sans-serif; | |
| ">{pred['display_word']}</span> | |
| </div> | |
| <span style=" | |
| color: #6591F4; | |
| font-weight: 600; | |
| font-size: 18px; | |
| ">{pred['probability']:.1f}%</span> | |
| </div> | |
| ''' | |
| html += '</div>' | |
| return html | |
| def append_word_from_radio(text, selection): | |
| """Append selected word to text when radio is selected""" | |
| global current_predictions | |
| if not selection or not current_predictions: | |
| return text | |
| # Extract rank from selection (format: "1. word (prob%)") | |
| try: | |
| rank = int(selection.split('.')[0]) | |
| if rank <= len(current_predictions): | |
| word = current_predictions[rank - 1]['raw_word'] | |
| return text + word | |
| except: | |
| pass | |
| return text | |
| # Custom CSS to match the original design | |
| custom_css = """ | |
| /* Solid blue background - apply to multiple selectors for HF Spaces compatibility */ | |
| body, html, #root, .gradio-app { | |
| background: white !important; | |
| min-height: 100vh !important; | |
| font-family: 'Open Sans', sans-serif !important; | |
| } | |
| .gradio-container, .app { | |
| background: transparent !important; | |
| } | |
| /* White card container - target multiple possible classes */ | |
| .main, .main.svelte-1kyws56, [class*="main"], .contain { | |
| background: white !important; | |
| padding: 0 !important; | |
| max-width: 800px !important; | |
| margin: 30px auto !important; | |
| width: 90% !important; | |
| } | |
| /* Title styling */ | |
| .markdown h1, .prose h1, .gradio-container h1, [class*="gradio-container"] .prose h1 { | |
| color: #333 !important; | |
| margin-bottom: 2px !important; | |
| font-size: 32px !important; | |
| text-align: center !important; | |
| margin-top: 20px !important; | |
| } | |
| h3, .markdown h3 { | |
| color: #333 !important; | |
| font-size: 18px !important; | |
| margin-top: 0px !important; | |
| padding-left: 40px !important; | |
| padding-right: 40px !important; | |
| padding-top: 0px !important; | |
| } | |
| /* Subtitle text styling */ | |
| .title-subtitle p, [class*="gradio-container"] .prose p, .prose p { | |
| text-align: center !important; | |
| color: #6c757d !important; | |
| margin-top: 0 !important; | |
| margin-bottom: 25px !important; | |
| font-size: 18px !important; | |
| font-weight: normal !important; | |
| } | |
| /* Instructional text styling */ | |
| .instruction-text p { | |
| color: #6c757d !important; | |
| font-style: italic !important; | |
| margin-top: 0px !important; | |
| margin-bottom: 15px !important; | |
| padding-left: 40px !important; | |
| padding-right: 40px !important; | |
| font-size: 14px !important; | |
| } | |
| /* Remove ALL borders from everything first */ | |
| * { | |
| border: none !important; | |
| box-shadow: none !important; | |
| outline: none !important; | |
| } | |
| /* Add padding to textbox block container for proper alignment */ | |
| .block:has(textarea), | |
| .block.padded:has(label) { | |
| padding-left: 40px !important; | |
| padding-right: 40px !important; | |
| } | |
| /* Alternative: target label containing textarea */ | |
| label:has(textarea) { | |
| margin-left: 0 !important; | |
| margin-right: 0 !important; | |
| } | |
| /* Then add back ONLY the textarea border */ | |
| textarea { | |
| border: 2px solid #e0e0e0 !important; | |
| border-radius: 8px !important; | |
| font-size: 20px !important; | |
| padding: 15px !important; | |
| line-height: 1.5 !important; | |
| font-family: inherit !important; | |
| box-shadow: none !important; | |
| outline: none !important; | |
| overflow-y: scroll !important; | |
| margin-top: 40px !important; | |
| margin-bottom: 40px !important; | |
| } | |
| textarea:focus { | |
| border: 2px solid #667eea !important; | |
| box-shadow: none !important; | |
| outline: none !important; | |
| } | |
| /* Prevent body from shifting when content changes */ | |
| body { | |
| overflow-y: scroll !important; | |
| } | |
| /* Match placeholder text size */ | |
| textarea::placeholder { | |
| font-size: 16px !important; | |
| color: #999 !important; | |
| } | |
| /* Hide the radio buttons but keep them functional */ | |
| #predictions-radio { | |
| display: none !important; | |
| } | |
| /* Prediction items hover effect enhancement */ | |
| .prediction-item:active { | |
| transform: translateX(5px) scale(0.98) !important; | |
| } | |
| /* Hide loading spinners and progress indicators */ | |
| .loader, .loading { | |
| display: none !important; | |
| } | |
| .progress-bar { | |
| display: none !important; | |
| } | |
| .pending, .generating { | |
| display: none !important; | |
| } | |
| /* Hide the "Generating" status text */ | |
| .eta-bar { | |
| display: none !important; | |
| } | |
| .padding { | |
| padding: 0px 10px !important; | |
| } | |
| """ | |
| # Create Gradio interface | |
| with gr.Blocks(css=custom_css, title="Next Word Prediction") as demo: | |
| gr.Markdown("""<center> | |
| <h1>Next Word Prediction</h1> | |
| <p>Based on GPT-2</p> | |
| </center>""") | |
| with gr.Row(): | |
| with gr.Column(): | |
| text_input = gr.Textbox( | |
| label="", | |
| placeholder="Enter your text here...", | |
| value="Never gonna give you up, never gonna let you", | |
| lines=1, | |
| max_lines=4, | |
| show_label=False | |
| ) | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("### Next Word Predictions") | |
| # HTML display for beautiful predictions | |
| predictions_display = gr.HTML() | |
| # Hidden radio for selection handling | |
| predictions_radio = gr.Radio( | |
| choices=[], | |
| elem_id="predictions-radio", | |
| visible=True, # Keep visible but hide with CSS | |
| label="" | |
| ) | |
| # Update predictions when text changes | |
| text_input.change( | |
| fn=get_next_word_predictions, | |
| inputs=[text_input], | |
| outputs=[predictions_display, predictions_radio], | |
| show_progress="hidden" | |
| ) | |
| # Handle selection from radio (triggered by JavaScript) | |
| predictions_radio.change( | |
| fn=append_word_from_radio, inputs=[text_input, predictions_radio], outputs=[text_input], show_progress="minimal" | |
| ) | |
| # Load initial predictions | |
| demo.load( | |
| fn=get_next_word_predictions, | |
| inputs=[text_input], | |
| outputs=[predictions_display, predictions_radio] | |
| ) | |
| # Launch the app | |
| if __name__ == "__main__": | |
| demo.launch() | |