Falguni commited on
Commit
4eef17c
·
1 Parent(s): e048cbb

Update methods export and cleanup pgn files

Browse files
Files changed (1) hide show
  1. src/util/pgn_util.py +27 -4
src/util/pgn_util.py CHANGED
@@ -1,5 +1,9 @@
 
1
  import chess.pgn
2
  import tempfile
 
 
 
3
 
4
 
5
  # Load game
@@ -9,12 +13,31 @@ def read_pgn(pgn_filepath):
9
  return game
10
 
11
 
12
- def export_pgn(game):
13
- # Create a temp file with .pgn extension that won't be auto-deleted
14
- with tempfile.NamedTemporaryFile(delete=False, suffix=".pgn", mode="w") as tmp:
 
 
 
15
  exporter = chess.pgn.FileExporter(tmp)
16
  game.accept(exporter)
17
- return tmp.name # Return the file path so Gradio can serve it
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
 
20
  def format_pv(pv_moves, board):
 
1
+ import logging
2
  import chess.pgn
3
  import tempfile
4
+ import os
5
+ import time
6
+ import glob
7
 
8
 
9
  # Load game
 
13
  return game
14
 
15
 
16
+ def export_pgn(game, tmp_dir="tmp_pgn"):
17
+ os.makedirs(tmp_dir, exist_ok=True)
18
+
19
+ with tempfile.NamedTemporaryFile(
20
+ delete=False, suffix=".pgn", dir=tmp_dir, mode="w", encoding="utf-8"
21
+ ) as tmp:
22
  exporter = chess.pgn.FileExporter(tmp)
23
  game.accept(exporter)
24
+ return tmp.name
25
+
26
+
27
+ def cleanup_tmp_pgn(tmp_dir="tmp_pgn", expire_seconds=300):
28
+ if not os.path.exists(tmp_dir):
29
+ return
30
+
31
+ now = time.time()
32
+ pgn_files = glob.glob(os.path.join(tmp_dir, "*.pgn"))
33
+
34
+ for file_path in pgn_files:
35
+ try:
36
+ if now - os.path.getmtime(file_path) > expire_seconds:
37
+ os.remove(file_path)
38
+ logging.info(f"Deleted: {file_path}")
39
+ except Exception as e:
40
+ logging.warning(f"Error deleting {file_path}: {e}")
41
 
42
 
43
  def format_pv(pv_moves, board):