from fastapi import FastAPI, Request, Form from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates from fastapi.staticfiles import StaticFiles import numpy as np import pickle import uvicorn import pickle import pandas as pd app = FastAPI() templates = Jinja2Templates(directory="templates") try: with open('final_3dprint_model.pkl', 'rb') as file: model = pickle.load(file) print("Model loaded successfully.") except Exception as e: print(f"Error loading model: {e}") model = None MODEL_FEATURES = [ 'layer_height', 'wall_thickness', 'infill_density', 'nozzle_temperature', 'bed_temperature', 'print_speed', 'fan_speed', 'infill_pattern_grid', 'infill_pattern_honeycomb', 'material_abs', 'material_pla' ] @app.get("/") def home(request: Request): """ Renders the main input form page. """ return templates.TemplateResponse("index.html", {"request": request}) @app.post("/predict") async def predict(request: Request): """ Receives form data, preprocesses it, makes a prediction, and re-renders the page with the results. """ if model is None: return templates.TemplateResponse("index.html", { "request": request, "prediction_text": "Error: Model could not be loaded." }) try: form_data = await request.form() input_data = {feature: 0 for feature in MODEL_FEATURES} input_data['layer_height'] = float(form_data['layer_height']) input_data['wall_thickness'] = int(form_data['wall_thickness']) input_data['infill_density'] = int(form_data['infill_density']) input_data['nozzle_temperature'] = int(form_data['nozzle_temperature']) input_data['bed_temperature'] = int(form_data['bed_temperature']) input_data['print_speed'] = int(form_data['print_speed']) input_data['fan_speed'] = int(form_data['fan_speed']) if form_data['infill_pattern'] == 'grid': input_data['infill_pattern_grid'] = 1 elif form_data['infill_pattern'] == 'honeycomb': input_data['infill_pattern_honeycomb'] = 1 if form_data['material'] == 'abs': input_data['material_abs'] = 1 elif form_data['material'] == 'pla': input_data['material_pla'] = 1 input_df = pd.DataFrame([input_data], columns=MODEL_FEATURES) prediction_array = model.predict(input_df) prediction_results = { 'roughness': prediction_array[0, 0], 'tension_strenght': prediction_array[0, 1], 'elongation': prediction_array[0, 2] } return templates.TemplateResponse("index.html", { "request": request, "prediction": prediction_results }) except Exception as e: return templates.TemplateResponse("index.html", { "request": request, "prediction": {"error": f"An error occurred: {e}"} }) if __name__ == "__main__": import uvicorn uvicorn.run("main:app", host="0.0.0.0", port=7860)