szili2011's picture
Update app.py
0a68069 verified
raw
history blame
5.04 kB
# app.py (Hardened and Debuggable Version)
import gradio as gr
import tensorflow as tf
import pickle
import numpy as np
# --- 1. CONFIGURATION & MODEL LOADING ---
MAX_SEQ_LENGTH = 30
print("--- App Starting Up ---")
print("Loading models and tokenizers...")
try:
successor_model = tf.keras.models.load_model('successor_model.h5')
with open('successor_model_tokenizers.pkl', 'rb') as f:
successor_tokenizers = pickle.load(f)
predecessor_model = tf.keras.models.load_model('predecessor_model.h5')
with open('predecessor_model_tokenizers.pkl', 'rb') as f:
predecessor_tokenizers = pickle.load(f)
print("Models and tokenizers loaded successfully.")
except Exception as e:
print(f"FATAL ERROR loading files: {e}")
successor_model, predecessor_model = None, None
# --- 2. THE CORE PREDICTION LOGIC (MODIFIED) ---
# This function now receives the actual model and tokenizer objects
def predict_next_state(model, tokenizers, current_unit, current_analogy, current_commentary):
if not model or not tokenizers:
return "Error: A required model or tokenizer is not loaded.", "Check server logs.", "---"
# Prepare input data
input_data = {'current_unit_name': [current_unit], 'current_analogy': [current_analogy], 'current_commentary': [current_commentary]}
processed_input = {}
for col, text_list in input_data.items():
sequences = tokenizers[col].texts_to_sequences(text_list)
padded_sequences = tf.keras.preprocessing.sequence.pad_sequences(sequences, maxlen=MAX_SEQ_LENGTH, padding='post')
processed_input[col] = padded_sequences
# Get AI prediction
predictions = model.predict(processed_input)
# Decode prediction back to text
target_texts = {}
output_cols = ['target_unit_name', 'target_analogy', 'target_commentary']
for i, col in enumerate(output_cols):
pred_indices = np.argmax(predictions[i], axis=-1)
predicted_sequence = tokenizers[col].sequences_to_texts(pred_indices)[0]
clean_text = ' '.join([word for word in predicted_sequence.split() if word not in ['<oov>', 'end']])
target_texts[col] = clean_text.strip()
# *** DEBUGGING PRINT ***
print(f"--- PREDICTION DECODED ---")
print(f"Decoded Unit Name: {target_texts['target_unit_name']}")
print(f"Decoded Analogy: {target_texts['target_analogy']}")
print("--------------------------")
# Handle "Infinity" Sentinel
if "end of knowledge" in target_texts['target_unit_name'].lower():
direction = "larger" if model == successor_model else "smaller"
prefix = "Giga-" if direction == "larger" else "pico-"
new_unit = f"{prefix}{current_unit}"
new_analogy = "A procedurally generated unit beyond the AI's known universe."
new_commentary = "This represents a step into true infinity, where rules replace learned knowledge."
return new_unit, new_analogy, new_commentary
else:
return target_texts['target_unit_name'], target_texts['target_analogy'], target_texts['target_commentary']
# --- WRAPPER FUNCTIONS (MODIFIED) ---
# These wrappers now pass the correct objects explicitly
def go_larger(unit, analogy, commentary):
print("\n>>> 'Go Larger' button clicked. Using SUCCESSOR model.")
return predict_next_state(successor_model, successor_tokenizers, unit, analogy, commentary)
def go_smaller(unit, analogy, commentary):
print("\n>>> 'Go Smaller' button clicked. Using PREDECESSOR model.")
return predict_next_state(predecessor_model, predecessor_tokenizers, unit, analogy, commentary)
# --- 3. THE GRADIO USER INTERFACE (No changes needed here) ---
initial_unit = "Byte"
initial_analogy = "a single character of text, like 'R'"
initial_commentary = "From binary choices, a building block is formed, ready to hold a single, recognizable symbol."
with gr.Blocks(theme=gr.themes.Soft(primary_hue="sky")) as demo:
gr.Markdown("# 🤖 Digital Scale Explorer AI")
# ... (the rest of the UI code is identical) ...
gr.Markdown("An AI trained from scratch to explore the infinite ladder of data sizes. Click the buttons to traverse the universe of data!")
with gr.Row():
unit_name_out = gr.Textbox(value=initial_unit, label="Unit Name", interactive=False)
analogy_out = gr.Textbox(value=initial_analogy, label="Analogy", lines=4, interactive=False)
commentary_out = gr.Textbox(value=initial_commentary, label="AI Commentary", lines=3, interactive=False)
with gr.Row():
smaller_btn = gr.Button("Go Smaller ⬇️", variant="secondary", size="lg")
larger_btn = gr.Button("Go Larger ⬆️", variant="primary", size="lg")
larger_btn.click(fn=go_larger, inputs=[unit_name_out, analogy_out, commentary_out], outputs=[unit_name_out, analogy_out, commentary_out])
smaller_btn.click(fn=go_smaller, inputs=[unit_name_out, analogy_out, commentary_out], outputs=[unit_name_out, analogy_out, commentary_out])
if __name__ == "__main__":
demo.launch()