Pawe艂 艁aba
commited on
Commit
路
9616708
1
Parent(s):
1728979
zmiany w index
Browse files
app.py
CHANGED
@@ -1,141 +1,121 @@
|
|
1 |
-
|
2 |
-
from fastapi import
|
|
|
3 |
import numpy as np
|
4 |
from tensorflow import keras
|
5 |
import json
|
6 |
import os
|
7 |
|
8 |
-
|
9 |
app = FastAPI()
|
10 |
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
|
16 |
class TicTacToeAI:
|
17 |
-
def __init__(self, model_path=
|
18 |
self.model_path = model_path
|
19 |
self.model = None
|
20 |
self.load_model()
|
21 |
-
|
22 |
def load_model(self):
|
23 |
"""Wczytuje model z pliku"""
|
24 |
if os.path.exists(self.model_path):
|
25 |
self.model = keras.models.load_model(self.model_path)
|
26 |
return True
|
27 |
return False
|
28 |
-
|
29 |
def get_move(self, board):
|
30 |
"""Zwraca najlepszy ruch dla danego stanu planszy"""
|
31 |
if self.model is None:
|
32 |
raise ValueError("Model nie zosta艂 wczytany")
|
33 |
-
|
34 |
board_array = np.array(board)
|
35 |
predictions = self.model.predict(board_array.reshape(1, -1), verbose=0)[0]
|
36 |
valid_moves = np.where(board_array == 0)[0]
|
37 |
-
|
38 |
if len(valid_moves) == 0:
|
39 |
raise ValueError("Brak dost臋pnych ruch贸w")
|
40 |
-
|
41 |
valid_predictions = [(i, pred) for i, pred in enumerate(predictions) if i in valid_moves]
|
42 |
return int(max(valid_predictions, key=lambda x: x[1])[0])
|
43 |
|
|
|
44 |
# Inicjalizacja AI
|
45 |
ai = TicTacToeAI()
|
46 |
|
47 |
|
48 |
-
@app.
|
49 |
-
def get_move():
|
50 |
"""
|
51 |
Endpoint do wykonania ruchu AI
|
52 |
-
|
53 |
-
Przyk艂adowe 偶膮danie:
|
54 |
-
{
|
55 |
-
"board": [0, 0, 0, 0, 1, 0, 0, 0, -1]
|
56 |
-
}
|
57 |
"""
|
58 |
try:
|
59 |
-
data = request.
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
if not all(x in [0, 1, -1] for x in board):
|
70 |
-
return jsonify({'error': 'Nieprawid艂owe warto艣ci na planszy'}), 400
|
71 |
-
|
72 |
move = ai.get_move(board)
|
73 |
-
|
74 |
-
return
|
75 |
-
'status': 'success',
|
76 |
-
'move': move
|
77 |
-
})
|
78 |
-
|
79 |
except Exception as e:
|
80 |
-
|
81 |
|
82 |
|
83 |
-
|
84 |
-
|
85 |
-
def add_game():
|
86 |
"""
|
87 |
Endpoint do dodania gry do pliku
|
88 |
-
|
89 |
-
Przyk艂adowe 偶膮danie:
|
90 |
-
{
|
91 |
-
"board": [0, 0, 0, 0, 1, 0, 0, 0, -1],
|
92 |
-
"win": true
|
93 |
-
}
|
94 |
"""
|
95 |
try:
|
96 |
-
data = request.
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
games_data.append({
|
117 |
-
'board': board,
|
118 |
-
'win': win
|
119 |
-
})
|
120 |
-
|
121 |
-
with open('gry.json', 'w') as file:
|
122 |
json.dump(games_data, file)
|
123 |
-
|
124 |
-
return jsonify({
|
125 |
-
'status': 'success'
|
126 |
-
})
|
127 |
-
|
128 |
-
except Exception as e:
|
129 |
-
return jsonify({'error': str(e)}), 500
|
130 |
|
|
|
|
|
|
|
131 |
|
132 |
|
133 |
-
@app.
|
134 |
-
def get_status():
|
135 |
"""Sprawdza status modelu"""
|
136 |
-
return
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException, Request
|
2 |
+
from fastapi.responses import JSONResponse, HTMLResponse
|
3 |
+
from fastapi.staticfiles import StaticFiles
|
4 |
import numpy as np
|
5 |
from tensorflow import keras
|
6 |
import json
|
7 |
import os
|
8 |
|
|
|
9 |
app = FastAPI()
|
10 |
|
11 |
+
# Obs艂uga plik贸w statycznych
|
12 |
+
app.mount("/public", StaticFiles(directory="public"), name="public")
|
13 |
+
|
14 |
+
|
15 |
+
@app.get("/", response_class=HTMLResponse)
|
16 |
+
async def read_root():
|
17 |
+
"""Wy艣wietla plik index.html"""
|
18 |
+
try:
|
19 |
+
with open("public/index.html", "r") as file:
|
20 |
+
return HTMLResponse(content=file.read(), status_code=200)
|
21 |
+
except FileNotFoundError:
|
22 |
+
raise HTTPException(status_code=404, detail="Plik index.html nie zosta艂 znaleziony")
|
23 |
|
24 |
|
25 |
class TicTacToeAI:
|
26 |
+
def __init__(self, model_path="model/model.keras"):
|
27 |
self.model_path = model_path
|
28 |
self.model = None
|
29 |
self.load_model()
|
30 |
+
|
31 |
def load_model(self):
|
32 |
"""Wczytuje model z pliku"""
|
33 |
if os.path.exists(self.model_path):
|
34 |
self.model = keras.models.load_model(self.model_path)
|
35 |
return True
|
36 |
return False
|
37 |
+
|
38 |
def get_move(self, board):
|
39 |
"""Zwraca najlepszy ruch dla danego stanu planszy"""
|
40 |
if self.model is None:
|
41 |
raise ValueError("Model nie zosta艂 wczytany")
|
42 |
+
|
43 |
board_array = np.array(board)
|
44 |
predictions = self.model.predict(board_array.reshape(1, -1), verbose=0)[0]
|
45 |
valid_moves = np.where(board_array == 0)[0]
|
46 |
+
|
47 |
if len(valid_moves) == 0:
|
48 |
raise ValueError("Brak dost臋pnych ruch贸w")
|
49 |
+
|
50 |
valid_predictions = [(i, pred) for i, pred in enumerate(predictions) if i in valid_moves]
|
51 |
return int(max(valid_predictions, key=lambda x: x[1])[0])
|
52 |
|
53 |
+
|
54 |
# Inicjalizacja AI
|
55 |
ai = TicTacToeAI()
|
56 |
|
57 |
|
58 |
+
@app.post("/move")
|
59 |
+
async def get_move(request: Request):
|
60 |
"""
|
61 |
Endpoint do wykonania ruchu AI
|
|
|
|
|
|
|
|
|
|
|
62 |
"""
|
63 |
try:
|
64 |
+
data = await request.json()
|
65 |
+
board = data.get("board")
|
66 |
+
|
67 |
+
if not board:
|
68 |
+
raise HTTPException(status_code=400, detail="Brak planszy w 偶膮daniu")
|
69 |
+
|
70 |
+
if len(board) != 9 or not all(x in [0, 1, -1] for x in board):
|
71 |
+
raise HTTPException(status_code=400, detail="Nieprawid艂owe dane planszy")
|
72 |
+
|
|
|
|
|
|
|
|
|
73 |
move = ai.get_move(board)
|
74 |
+
|
75 |
+
return JSONResponse(content={"status": "success", "move": move})
|
|
|
|
|
|
|
|
|
76 |
except Exception as e:
|
77 |
+
raise HTTPException(status_code=500, detail=str(e))
|
78 |
|
79 |
|
80 |
+
@app.post("/game")
|
81 |
+
async def add_game(request: Request):
|
|
|
82 |
"""
|
83 |
Endpoint do dodania gry do pliku
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
"""
|
85 |
try:
|
86 |
+
data = await request.json()
|
87 |
+
board = data.get("board")
|
88 |
+
win = data.get("win")
|
89 |
+
|
90 |
+
if not board or win is None:
|
91 |
+
raise HTTPException(status_code=400, detail="Brak planszy lub informacji o wygranej w 偶膮daniu")
|
92 |
+
|
93 |
+
if len(board) != 9 or not all(x in [0, 1, -1] for x in board):
|
94 |
+
raise HTTPException(status_code=400, detail="Nieprawid艂owe dane planszy")
|
95 |
+
|
96 |
+
if os.path.exists("gry.json"):
|
97 |
+
with open("gry.json", "r") as file:
|
98 |
+
games_data = json.load(file)
|
99 |
+
else:
|
100 |
+
games_data = []
|
101 |
+
|
102 |
+
games_data.append({"board": board, "win": win})
|
103 |
+
|
104 |
+
with open("gry.json", "w") as file:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
json.dump(games_data, file)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
|
107 |
+
return JSONResponse(content={"status": "success"})
|
108 |
+
except Exception as e:
|
109 |
+
raise HTTPException(status_code=500, detail=str(e))
|
110 |
|
111 |
|
112 |
+
@app.get("/status")
|
113 |
+
async def get_status():
|
114 |
"""Sprawdza status modelu"""
|
115 |
+
return JSONResponse(
|
116 |
+
content={
|
117 |
+
"status": "success",
|
118 |
+
"model_loaded": ai.model is not None,
|
119 |
+
"model_path": ai.model_path,
|
120 |
+
}
|
121 |
+
)
|