Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
import pickle
|
| 5 |
+
import numpy as np
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
# --- 1. CONFIGURATION & MODEL LOADING ---
|
| 9 |
+
# This section loads your trained AI models and the tokenizers needed to understand text.
|
| 10 |
+
MAX_SEQ_LENGTH = 30 # Must match the value used during training!
|
| 11 |
+
|
| 12 |
+
print("Loading models and tokenizers...")
|
| 13 |
+
try:
|
| 14 |
+
# Load the "Go Larger" model and its vocabulary
|
| 15 |
+
successor_model = tf.keras.models.load_model('successor_model.h5')
|
| 16 |
+
with open('successor_model_tokenizers.pkl', 'rb') as f:
|
| 17 |
+
successor_tokenizers = pickle.load(f)
|
| 18 |
+
|
| 19 |
+
# Load the "Go Smaller" model and its vocabulary
|
| 20 |
+
predecessor_model = tf.keras.models.load_model('predecessor_model.h5')
|
| 21 |
+
with open('predecessor_model_tokenizers.pkl', 'rb') as f:
|
| 22 |
+
predecessor_tokenizers = pickle.load(f)
|
| 23 |
+
|
| 24 |
+
print("Models and tokenizers loaded successfully.")
|
| 25 |
+
except Exception as e:
|
| 26 |
+
# This helps debug issues on Hugging Face Spaces if a file is missing
|
| 27 |
+
print(f"FATAL ERROR loading files: {e}")
|
| 28 |
+
successor_model, predecessor_model = None, None
|
| 29 |
+
|
| 30 |
+
# --- 2. THE CORE PREDICTION LOGIC ---
|
| 31 |
+
# This function is the "brain" of the application.
|
| 32 |
+
def predict_next_state(direction, current_unit, current_analogy, current_commentary):
|
| 33 |
+
# Safety check in case models failed to load
|
| 34 |
+
if not all([successor_model, predecessor_model]):
|
| 35 |
+
return "Error: Models are not loaded.", "Please check the server logs on Hugging Face.", "---"
|
| 36 |
+
|
| 37 |
+
# A. Select the correct AI model and tokenizers based on user's click
|
| 38 |
+
model = successor_model if direction == "larger" else predecessor_model
|
| 39 |
+
tokenizers = successor_tokenizers if direction == "larger" else predecessor_tokenizers
|
| 40 |
+
|
| 41 |
+
# B. Prepare the input data for the model
|
| 42 |
+
# The input text must be converted to numbers exactly as it was during training.
|
| 43 |
+
input_data = {
|
| 44 |
+
'current_unit_name': [current_unit],
|
| 45 |
+
'current_analogy': [current_analogy],
|
| 46 |
+
'current_commentary': [current_commentary]
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
processed_input = {}
|
| 50 |
+
for col, text_list in input_data.items():
|
| 51 |
+
sequences = tokenizers[col].texts_to_sequences(text_list)
|
| 52 |
+
padded_sequences = tf.keras.preprocessing.sequence.pad_sequences(sequences, maxlen=MAX_SEQ_LENGTH, padding='post')
|
| 53 |
+
processed_input[col] = padded_sequences
|
| 54 |
+
|
| 55 |
+
# C. Get the AI's prediction
|
| 56 |
+
predictions = model.predict(processed_input)
|
| 57 |
+
|
| 58 |
+
# D. Decode the prediction from numbers back to human-readable text
|
| 59 |
+
target_texts = {}
|
| 60 |
+
output_cols = ['target_unit_name', 'target_analogy', 'target_commentary']
|
| 61 |
+
|
| 62 |
+
for i, col in enumerate(output_cols):
|
| 63 |
+
# The model outputs probabilities; we take the most likely token (word) at each step.
|
| 64 |
+
pred_indices = np.argmax(predictions[i], axis=-1)
|
| 65 |
+
# Use the tokenizer to convert the sequence of indices back into a sentence.
|
| 66 |
+
predicted_sequence = tokenizers[col].sequences_to_texts(pred_indices)[0]
|
| 67 |
+
# Clean up padding and unknown words
|
| 68 |
+
target_texts[col] = predicted_sequence.replace('<oov>', '').replace(' end', '').strip()
|
| 69 |
+
|
| 70 |
+
# E. Handle the "Infinity" Sentinel
|
| 71 |
+
# Check if the AI returned our special signal.
|
| 72 |
+
if "end of knowledge" in target_texts['target_unit_name'].lower():
|
| 73 |
+
# If so, switch to the simple rule-based procedural engine.
|
| 74 |
+
prefix = "Giga-" if direction == "larger" else "pico-"
|
| 75 |
+
new_unit = f"{prefix}{current_unit}"
|
| 76 |
+
new_analogy = "A procedurally generated unit beyond the AI's known universe."
|
| 77 |
+
new_commentary = "This represents a step into true infinity, where rules replace learned knowledge."
|
| 78 |
+
return new_unit, new_analogy, new_commentary
|
| 79 |
+
else:
|
| 80 |
+
# Otherwise, return the AI's generated response.
|
| 81 |
+
return target_texts['target_unit_name'], target_texts['target_analogy'], target_texts['target_commentary']
|
| 82 |
+
|
| 83 |
+
# Wrapper functions for the buttons
|
| 84 |
+
def go_larger(unit, analogy, commentary):
|
| 85 |
+
return predict_next_state("larger", unit, analogy, commentary)
|
| 86 |
+
|
| 87 |
+
def go_smaller(unit, analogy, commentary):
|
| 88 |
+
return predict_next_state("smaller", unit, analogy, commentary)
|
| 89 |
+
|
| 90 |
+
# --- 3. THE GRADIO USER INTERFACE ---
|
| 91 |
+
# This section defines the layout and interactivity of the web page.
|
| 92 |
+
initial_unit = "Byte"
|
| 93 |
+
initial_analogy = "A single character of text, like 'R'"
|
| 94 |
+
initial_commentary = "From binary choices, a building block is formed, ready to hold a single, recognizable symbol."
|
| 95 |
+
|
| 96 |
+
# Use gr.Blocks for a custom layout
|
| 97 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="sky")) as demo:
|
| 98 |
+
gr.Markdown("# 🤖 Digital Scale Explorer AI")
|
| 99 |
+
gr.Markdown("An AI trained from scratch to explore the infinite ladder of data sizes. Click the buttons to traverse the universe of data!")
|
| 100 |
+
|
| 101 |
+
with gr.Row():
|
| 102 |
+
# Define the output text boxes
|
| 103 |
+
unit_name_out = gr.Textbox(value=initial_unit, label="Unit Name", interactive=False, elem_id="unit_name_style")
|
| 104 |
+
analogy_out = gr.Textbox(value=initial_analogy, label="Analogy", lines=4, interactive=False, elem_id="analogy_style")
|
| 105 |
+
commentary_out = gr.Textbox(value=initial_commentary, label="AI Commentary", lines=3, interactive=False, elem_id="commentary_style")
|
| 106 |
+
|
| 107 |
+
with gr.Row():
|
| 108 |
+
# Define the buttons
|
| 109 |
+
smaller_btn = gr.Button("Go Smaller ⬇️", variant="secondary", size="lg")
|
| 110 |
+
larger_btn = gr.Button("Go Larger ⬆️", variant="primary", size="lg")
|
| 111 |
+
|
| 112 |
+
# Connect the "Go Larger" button to its function
|
| 113 |
+
larger_btn.click(
|
| 114 |
+
fn=go_larger,
|
| 115 |
+
inputs=[unit_name_out, analogy_out, commentary_out],
|
| 116 |
+
outputs=[unit_name_out, analogy_out, commentary_out]
|
| 117 |
+
)
|
| 118 |
+
# Connect the "Go Smaller" button to its function
|
| 119 |
+
smaller_btn.click(
|
| 120 |
+
fn=go_smaller,
|
| 121 |
+
inputs=[unit_name_out, analogy_out, commentary_out],
|
| 122 |
+
outputs=[unit_name_out, analogy_out, commentary_out]
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# Launch the app when the script is run
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
demo.launch()
|