Skip to content

Commit 0055b52

Browse files
feat: port to new endpoints + move towards adding modal before using maia2
1 parent 9c82b2d commit 0055b52

File tree

6 files changed

+68
-79
lines changed

6 files changed

+68
-79
lines changed

src/api/analysis/analysis.ts

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -472,26 +472,14 @@ export const getClientAnalyzedTournamentGame = async (
472472
} as any as ClientAnalyzedGame
473473
}
474474

475-
export const getClientAnalyzedLichessGame = async (
476-
id: string,
477-
pgn: string,
478-
maia_model = 'maia_kdd_1500',
479-
) => {
480-
const res = await fetch(
481-
buildUrl(
482-
'analysis/analyze_user_game?' +
483-
new URLSearchParams({
484-
maia_model,
485-
}),
486-
),
487-
{
488-
method: 'POST',
489-
body: pgn,
490-
headers: {
491-
'Content-Type': 'text/plain',
492-
},
475+
export const getClientAnalyzedLichessGame = async (id: string, pgn: string) => {
476+
const res = await fetch(buildUrl('analysis/analyze_user_game'), {
477+
method: 'POST',
478+
body: pgn,
479+
headers: {
480+
'Content-Type': 'text/plain',
493481
},
494-
)
482+
})
495483

496484
if (res.status === 401) {
497485
throw new Error('Unauthorized')
@@ -580,14 +568,12 @@ export const getClientAnalyzedLichessGame = async (
580568
export const getClientAnalyzedUserGame = async (
581569
id: string,
582570
game_type: 'play' | 'hand' | 'brain',
583-
maia_model = 'maia_kdd_1500',
584571
) => {
585572
const res = await fetch(
586573
buildUrl(
587574
`analysis/user/analyze_user_maia_game/${id}?` +
588575
new URLSearchParams({
589576
game_type,
590-
maia_model,
591577
}),
592578
),
593579
{

src/hooks/useAnalysisController/useAnalysisController.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ export const useAnalysisController = (
5959
const board = new Chess(game.moves[controller.currentIndex].board)
6060

6161
;(async () => {
62-
if (!maia.ready || maiaEvaluations[controller.currentIndex]) return
62+
if (maia?.status !== 'ready' || maiaEvaluations[controller.currentIndex])
63+
return
6364

6465
const { result } = await maia.batchEvaluate(
6566
Array(9).fill(board.fen()),
@@ -86,7 +87,7 @@ export const useAnalysisController = (
8687
return newEvaluations
8788
})
8889
})()
89-
}, [controller.currentIndex, game.type, maia.ready])
90+
}, [controller.currentIndex, game.type, maia?.status])
9091

9192
useEffect(() => {
9293
if (game.type === 'tournament') return
@@ -398,8 +399,8 @@ export const useAnalysisController = (
398399
}, [controller.currentIndex, currentMove, game.availableMoves])
399400

400401
return {
402+
maia,
401403
move,
402-
data: {},
403404
moves,
404405
controller,
405406
currentMaiaModel,
Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
1-
import { useMemo } from 'react'
1+
import { useState, useMemo, useEffect } from 'react'
22

33
import Maia from 'src/utils/maia2'
44

55
export const useMaiaEngine = () => {
6-
const maia = useMemo(() => {
7-
const model = new Maia({ model: '/maia2/maia_rapid.onnx' })
8-
return model
6+
const [maia, setMaia] = useState<Maia>()
7+
8+
useEffect(() => {
9+
setMaia(new Maia({ model: '/maia2/maia_rapid.onnx', type: 'rapid' }))
910
}, [])
1011

12+
// const maia = useMemo(() => {
13+
// const model = new Maia({ model: '/maia2/maia_rapid.onnx', type: 'rapid' })
14+
// return model
15+
// }, [])
16+
1117
return maia
1218
}

src/pages/analysis/[...id].tsx

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,7 @@ const Analysis: React.FC<Props> = ({
237237
},
238238
]
239239
const {
240+
maia,
240241
move,
241242
moves,
242243
controller,
@@ -576,6 +577,15 @@ const Analysis: React.FC<Props> = ({
576577
content="Collection of chess training and analysis tools centered around Maia."
577578
/>
578579
</Head>
580+
{maia?.status !== 'ready' ? (
581+
<>
582+
<div className="absolute left-0 top-0 z-50 flex h-screen w-screen flex-col bg-black">
583+
<p className="text-white">{maia?.status}</p>
584+
</div>
585+
</>
586+
) : (
587+
<></>
588+
)}
579589
<GameControllerContext.Provider value={{ ...controller }}>
580590
{analyzedGame && (isMobile ? mobileLayout : desktopLayout)}
581591
</GameControllerContext.Provider>

src/utils/maia2/model.ts

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,38 +4,58 @@ import { mirrorMove, preprocess, allPossibleMovesReversed } from './utils'
44

55
class Maia {
66
public model!: InferenceSession
7-
public ready: boolean
7+
public type: 'rapid' | 'blitz'
8+
public status: 'loading' | 'no-cache' | 'downloading' | 'ready'
89

9-
constructor(options: { model: string }) {
10-
this.ready = false
10+
constructor(options: { model: string; type: 'rapid' | 'blitz' }) {
11+
this.status = 'loading'
12+
this.type = options.type ?? 'rapid'
1113
;(async () => {
1214
try {
13-
const buffer = await this.getCachedModel(options.model)
14-
this.model = await InferenceSession.create(buffer)
15-
16-
this.ready = true
15+
console.log('Getting cached')
16+
const buffer = await this.getCachedModel(options.model, options.type)
17+
await this.initializeModel(buffer)
1718
} catch (e) {
18-
this.ready = false
19+
console.log('Missing cache')
20+
this.status = 'no-cache'
1921
}
2022
})()
2123
}
2224

23-
private async getCachedModel(url: string): Promise<ArrayBuffer> {
24-
const cache = await caches.open('maia2-model')
25+
public getStatus() {
26+
return this.status
27+
}
28+
29+
public async getCachedModel(
30+
url: string,
31+
type: 'rapid' | 'blitz',
32+
): Promise<ArrayBuffer> {
33+
const cache = await caches.open(`MAIA2-${type.toUpperCase()}-MODEL`)
2534
const response = await cache.match(url)
2635
if (response) {
2736
return response.arrayBuffer()
2837
} else {
29-
const response = await fetch(url)
30-
if (response.ok) {
31-
await cache.put(url, response.clone())
32-
return response.arrayBuffer()
33-
} else {
34-
throw new Error('Failed to fetch model')
35-
}
38+
throw new Error('Model not found in cache')
3639
}
3740
}
3841

42+
public async fetchModel(url: string, type: 'rapid' | 'blitz') {
43+
const cache = await caches.open(`MAIA2-${type.toUpperCase()}-MODEL`)
44+
const response = await fetch(url)
45+
if (response.ok) {
46+
await cache.put(url, response.clone())
47+
return response.arrayBuffer()
48+
} else {
49+
throw new Error('Failed to fetch model')
50+
}
51+
}
52+
53+
public async initializeModel(buffer: ArrayBuffer) {
54+
this.model = await InferenceSession.create(buffer)
55+
this.status = 'ready'
56+
console.log('initialized')
57+
}
58+
3959
/**
4060
* Evaluates a given chess position using the Maia model.
4161
*

src/utils/maia2/utils.ts

Lines changed: 0 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -288,38 +288,4 @@ function swapColorsInRank(rank: string): string {
288288
return swappedRank
289289
}
290290

291-
/**
292-
* Swap castling rights between white and black.
293-
*
294-
* @param castling - The castling rights string.
295-
* @returns The swapped castling rights string.
296-
*/
297-
function swapCastlingRights(castling: string): string {
298-
const castlingMap: { [key: string]: string } = {
299-
K: 'k',
300-
Q: 'q',
301-
k: 'K',
302-
q: 'Q',
303-
}
304-
return castling
305-
.split('')
306-
.map((char) => castlingMap[char] || char)
307-
.join('')
308-
}
309-
310-
/**
311-
* Mirrors the en passant target square by flipping the rank.
312-
* @param square The en passant target square to be mirrored.
313-
* @returns The mirrored en passant target square.
314-
*/
315-
function mirrorEnPassant(square: string): string {
316-
const file = square[0]
317-
const rank = square[1]
318-
319-
// Flip the rank: '1' ↔ '8', '2' ↔ '7', etc.
320-
const mirroredRank = (9 - parseInt(rank, 10)).toString()
321-
322-
return `${file}${mirroredRank}`
323-
}
324-
325291
export { preprocess, mirrorMove, allPossibleMovesReversed }

0 commit comments

Comments
 (0)