File size: 3,480 Bytes
c420a2a 9616708 e1e7a0d e9d5caf d69ff2d 2434569 9616708 9eac87f d69ff2d e9d5caf e1e7a0d 9616708 e1e7a0d 9616708 e1e7a0d 9616708 e1e7a0d 9616708 e1e7a0d 9616708 e1e7a0d 9616708 e1e7a0d 9616708 e1e7a0d 9616708 c420a2a e1e7a0d 9616708 e1e7a0d 9616708 c420a2a e1e7a0d 9616708 e1e7a0d 9616708 c420a2a e1e7a0d 9616708 e1e7a0d c420a2a 9616708 e1e7a0d 9616708 e1e7a0d c420a2a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
import numpy as np
from tensorflow import keras
import json
import os
# Ustawienie prefiksu aplikacji
app = FastAPI(root_path="/spaces/labapawel/tictactoe")
# Montowanie katalogu publicznego
app.mount("/static", StaticFiles(directory="public"), name="static")
@app.get("/", response_class=HTMLResponse)
async def read_root():
try:
with open("public/index.html", "r") as file:
return HTMLResponse(content=file.read(), status_code=200)
except FileNotFoundError:
return HTMLResponse(content="Plik index.html nie został znaleziony", status_code=404)
class TicTacToeAI:
def __init__(self, model_path="model/model.keras"):
self.model_path = model_path
self.model = None
self.load_model()
def load_model(self):
"""Wczytuje model z pliku"""
if os.path.exists(self.model_path):
self.model = keras.models.load_model(self.model_path)
return True
return False
def get_move(self, board):
"""Zwraca najlepszy ruch dla danego stanu planszy"""
if self.model is None:
raise ValueError("Model nie został wczytany")
board_array = np.array(board)
predictions = self.model.predict(board_array.reshape(1, -1), verbose=0)[0]
valid_moves = np.where(board_array == 0)[0]
if len(valid_moves) == 0:
raise ValueError("Brak dostępnych ruchów")
valid_predictions = [(i, pred) for i, pred in enumerate(predictions) if i in valid_moves]
return int(max(valid_predictions, key=lambda x: x[1])[0])
# Inicjalizacja AI
ai = TicTacToeAI()
@app.post("/move")
async def get_move(data: dict):
"""
Endpoint do wykonania ruchu AI
"""
try:
board = data.get("board")
if not board:
raise HTTPException(status_code=400, detail="Brak planszy w żądaniu")
if len(board) != 9 or not all(x in [0, 1, -1] for x in board):
raise HTTPException(status_code=400, detail="Nieprawidłowe dane planszy")
move = ai.get_move(board)
return {"status": "success", "move": move}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/game")
async def add_game(data: dict):
"""
Endpoint do dodania gry do pliku
"""
try:
board = data.get("board")
win = data.get("win")
if not board or win is None:
raise HTTPException(status_code=400, detail="Brak planszy lub informacji o wygranej w żądaniu")
if len(board) != 9 or not all(x in [0, 1, -1] for x in board):
raise HTTPException(status_code=400, detail="Nieprawidłowe dane planszy")
if os.path.exists("gry.json"):
with open("gry.json", "r") as file:
games_data = json.load(file)
else:
games_data = []
games_data.append({"board": board, "win": win})
with open("gry.json", "w") as file:
json.dump(games_data, file)
return {"status": "success"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/status")
async def get_status():
"""Sprawdza status modelu"""
return {
"status": "success",
"model_loaded": ai.model is not None,
"model_path": ai.model_path,
}
|