File size: 4,048 Bytes
e1e7a0d e9d5caf dd9b72e e1e7a0d e9d5caf e1e7a0d eeff95a c54e371 e1e7a0d c54e371 e1e7a0d c54e371 e1e7a0d 52eb98a |
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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
# app.py
from flask import Flask, request, jsonify
from flask_cors import CORS
import numpy as np
from tensorflow import keras
import json
import os
app = Flask(__name__, static_folder="public")
CORS(app)
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.route("/")
def home():
return render_template("public/index.html")
@app.route('/move', methods=['POST'])
def get_move():
"""
Endpoint do wykonania ruchu AI
Przykładowe żądanie:
{
"board": [0, 0, 0, 0, 1, 0, 0, 0, -1]
}
"""
try:
data = request.get_json()
if 'board' not in data:
return jsonify({'error': 'Brak planszy w żądaniu'}), 400
board = data['board']
if len(board) != 9:
return jsonify({'error': 'Nieprawidłowy rozmiar planszy'}), 400
if not all(x in [0, 1, -1] for x in board):
return jsonify({'error': 'Nieprawidłowe wartości na planszy'}), 400
move = ai.get_move(board)
return jsonify({
'status': 'success',
'move': move
})
except Exception as e:
return jsonify({'error': str(e)}), 500
# dodaj posta dodającego do gry.json kolejne wygrane i przegrane, jako parametry dostaniesz board i win budowa pliku [{"board":[-1,1,0,-1,1,0,0,1,-1],"win":true}]
@app.route('/game', methods=['POST'])
def add_game():
"""
Endpoint do dodania gry do pliku
Przykładowe żądanie:
{
"board": [0, 0, 0, 0, 1, 0, 0, 0, -1],
"win": true
}
"""
try:
data = request.get_json()
if 'board' not in data:
return jsonify({'error': 'Brak planszy w żądaniu'}), 400
if 'win' not in data:
return jsonify({'error': 'Brak informacji o wygranej w żądaniu'}), 400
board = data['board']
win = data['win']
if len(board) != 9:
return jsonify({'error': 'Nieprawidłowy rozmiar planszy'}), 400
if not all(x in [0, 1, -1] for x in board):
return jsonify({'error': 'Nieprawidłowe wartości na planszy'}), 400
with open('gry.json', 'r') as file:
games_data = json.load(file)
games_data.append({
'board': board,
'win': win
})
with open('gry.json', 'w') as file:
json.dump(games_data, file)
return jsonify({
'status': 'success'
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/status', methods=['GET'])
def get_status():
"""Sprawdza status modelu"""
return jsonify({
'status': 'success',
'model_loaded': ai.model is not None,
'model_path': ai.model_path
})
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860) |