Spaces:
Sleeping
Sleeping
from flask import Flask, request, render_template | |
import os | |
import json | |
import numpy as np | |
from Vit_concept import run_inference, model | |
from GP import genetic_programming | |
app = Flask(__name__) | |
UPLOAD_FOLDER = 'uploads' | |
os.makedirs(UPLOAD_FOLDER, exist_ok=True) | |
def tolist_safe(obj): | |
if isinstance(obj, np.ndarray): | |
return obj.tolist() | |
return obj | |
def index(): | |
return render_template('index.html') | |
def upload(): | |
if 'file' not in request.files: | |
return "No file part" | |
file = request.files['file'] | |
if file.filename == '': | |
return "No selected file" | |
filepath = os.path.join(UPLOAD_FOLDER, file.filename) | |
file.save(filepath) | |
with open(filepath, 'r') as f: | |
data = json.load(f) | |
input_output_pairs = [] | |
predicted_HLCs = [] | |
for sample in data.get("train", []): | |
input_grid = sample["input"] | |
output_grid = sample["output"] | |
concept_label, _ = run_inference(model, input_grid, output_grid) | |
predicted_HLCs.append(concept_label) | |
input_output_pairs.append((input_grid, output_grid)) | |
predicted_HLCs = list(set(predicted_HLCs)) | |
best_program, generations = genetic_programming( | |
input_output_pairs=input_output_pairs, | |
population_size=300, | |
generations=500, | |
mutation_rate=0.2, | |
crossover_rate=0.7, | |
max_depth=3, | |
predicted_HLCs=predicted_HLCs | |
) | |
# Convert train pairs to plain lists | |
input_output_pairs = [(tolist_safe(i), tolist_safe(o)) for i, o in input_output_pairs] | |
# Prepare test pairs as well | |
test_pairs = [(tolist_safe(sample["input"]), tolist_safe(sample["output"])) for sample in data.get("test", [])] | |
# Prepare final program evaluation display | |
last_input = input_output_pairs[-1][0] if input_output_pairs else [] | |
last_ground_truth = input_output_pairs[-1][1] if input_output_pairs else [] | |
try: | |
predicted_output = tolist_safe(best_program.evaluate(last_input)) | |
except Exception as e: | |
print("Error during best_program evaluation:", e) | |
predicted_output = [["ERROR"]] | |
return render_template("results.html", | |
hlcs=predicted_HLCs, | |
input_output_pairs=input_output_pairs, | |
test_pairs=test_pairs, | |
best_program=str(best_program), | |
last_input=last_input, | |
last_ground_truth=last_ground_truth, | |
predicted_output=predicted_output) | |
if __name__ == '__main__': | |
app.run(host="0.0.0.0", port=7860) | |