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"
Error: {str(e)}
"
return error_html, gr.update(choices=[], value=None)
def create_predictions_html(predictions):
"""Create beautiful HTML for predictions"""
if not predictions:
return "Enter some text to see predictions...
"
html = ''
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'''
{pred['display_word']}
{pred['probability']:.1f}%
'''
html += '
'
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("""
Next Word Prediction
Based on GPT-2
""")
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()