Parth4105 commited on
Commit
fcefb8b
·
verified ·
1 Parent(s): 5ab9019

Upload 4 files

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ tests.db filter=lfs diff=lfs merge=lfs -text
gold_dataset_test_final.json ADDED
The diff for this file is too large to render. See raw diff
 
ingest_tests.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ingest_tests.py
3
+ ---------------
4
+ Ingests Cricsheet Test match JSON files (tests_json.zip or a directory of
5
+ .json files) into a SQLite database using schema_tests.sql.
6
+
7
+ Usage:
8
+ python ingest_tests.py
9
+
10
+ Paths are configured in the Configuration section below.
11
+ """
12
+
13
+ import os
14
+ import json
15
+ import zipfile
16
+ import sqlite3
17
+ import logging
18
+ import time
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Configuration
22
+ # ---------------------------------------------------------------------------
23
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
24
+ DB_PATH = os.path.join(BASE_DIR, 'tests.db')
25
+ SCHEMA_PATH = os.path.join(BASE_DIR, 'schema_tests.sql')
26
+ LOG_PATH = os.path.join(BASE_DIR, 'ingestion_tests.log')
27
+
28
+ # Source: either a zip file OR a directory of .json files.
29
+ # The script will prefer the zip if it exists.
30
+ JSON_ZIP_PATH = os.path.join(BASE_DIR, 'tests_json.zip')
31
+ JSON_DIR_PATH = os.path.join(BASE_DIR, 'tests_json') # fallback directory
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Logging
35
+ # ---------------------------------------------------------------------------
36
+ logging.basicConfig(
37
+ filename=LOG_PATH,
38
+ level=logging.INFO,
39
+ format='%(asctime)s - %(levelname)s - %(message)s',
40
+ filemode='w'
41
+ )
42
+
43
+
44
+ # ---------------------------------------------------------------------------
45
+ # Database setup
46
+ # ---------------------------------------------------------------------------
47
+ def create_database():
48
+ """Reads schema_tests.sql and (re)creates the database."""
49
+ if os.path.exists(DB_PATH):
50
+ os.remove(DB_PATH)
51
+ print(f"Creating database at {DB_PATH} ...")
52
+ with open(SCHEMA_PATH, 'r') as f:
53
+ schema = f.read()
54
+ conn = sqlite3.connect(DB_PATH)
55
+ conn.execute("PRAGMA foreign_keys = ON;")
56
+ conn.executescript(schema)
57
+ conn.commit()
58
+ conn.close()
59
+ print("Database created successfully.")
60
+
61
+
62
+ # ---------------------------------------------------------------------------
63
+ # Core processing
64
+ # ---------------------------------------------------------------------------
65
+ def process_file(db_conn, file_content: bytes, filename: str):
66
+ """
67
+ Parses a single JSON file (as bytes) and inserts all records into the DB.
68
+ Raises on unrecoverable errors so the caller can skip the file.
69
+ """
70
+ cursor = db_conn.cursor()
71
+ match_id = int(os.path.splitext(filename)[0])
72
+ logging.info(f"--- Processing {filename} ---")
73
+
74
+ data = json.loads(file_content)
75
+ info = data.get('info', {})
76
+
77
+ # -----------------------------------------------------------------------
78
+ # Build player registry for this file
79
+ # -----------------------------------------------------------------------
80
+ player_registry_raw = info.get('registry', {}).get('people', {})
81
+ if not player_registry_raw:
82
+ raise ValueError(f"No registry.people in {filename}")
83
+
84
+ registry = {
85
+ name.strip(): pid
86
+ for name, pid in player_registry_raw.items()
87
+ if name and pid
88
+ }
89
+
90
+ # Upsert all players found in this file
91
+ cursor.executemany(
92
+ "INSERT OR IGNORE INTO Players (player_id, player_name) VALUES (?, ?)",
93
+ [(pid, name) for name, pid in registry.items()]
94
+ )
95
+
96
+ def pid(name):
97
+ """Resolve common name -> player_id via the file's registry."""
98
+ if not name or not isinstance(name, str):
99
+ return None
100
+ return registry.get(name.strip())
101
+
102
+ # -----------------------------------------------------------------------
103
+ # Matches
104
+ # -----------------------------------------------------------------------
105
+ dates = info.get('dates', [''])
106
+ start_date = dates[0] if dates else ''
107
+ end_date = dates[-1] if len(dates) > 1 else None
108
+
109
+ outcome = info.get('outcome', {})
110
+ winner = outcome.get('winner') # None → draw/no result
111
+
112
+ by = outcome.get('by', {})
113
+ if by:
114
+ result_type = list(by.keys())[0] # 'runs' or 'wickets'
115
+ result_margin = list(by.values())[0]
116
+ else:
117
+ # 'draw', 'tie', 'no result', etc.
118
+ result_type = outcome.get('result', 'no result')
119
+ result_margin = None
120
+
121
+ event = info.get('event', {})
122
+ series_name = event.get('name')
123
+ match_type_num = event.get('match_number')
124
+
125
+ officials = info.get('officials', {})
126
+ umpires = officials.get('umpires', [])
127
+ tv_umpire_list = officials.get('tv_umpires', [])
128
+ referee_list = officials.get('match_referees', [])
129
+
130
+ pom_name = (info.get('player_of_match') or [None])[0]
131
+ pom_id = pid(pom_name) if pom_name else None
132
+
133
+ teams = info.get('teams', ['', ''])
134
+
135
+ cursor.execute("""
136
+ INSERT INTO Matches (
137
+ match_id, season, start_date, end_date, venue, city,
138
+ series_name, match_type_number, gender, team_type,
139
+ team1, team2,
140
+ toss_winner, toss_decision,
141
+ match_winner, result_type, result_margin,
142
+ player_of_match_id,
143
+ umpire1, umpire2, tv_umpire, match_referee
144
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
145
+ """, (
146
+ match_id,
147
+ str(info.get('season', '')),
148
+ start_date, end_date,
149
+ info.get('venue', 'Unknown'),
150
+ info.get('city'),
151
+ series_name, match_type_num,
152
+ info.get('gender'),
153
+ info.get('team_type'),
154
+ teams[0] if len(teams) > 0 else '',
155
+ teams[1] if len(teams) > 1 else '',
156
+ info.get('toss', {}).get('winner', 'Unknown'),
157
+ info.get('toss', {}).get('decision', 'Unknown'),
158
+ winner, result_type, result_margin,
159
+ pom_id,
160
+ umpires[0] if len(umpires) > 0 else None,
161
+ umpires[1] if len(umpires) > 1 else None,
162
+ tv_umpire_list[0] if tv_umpire_list else None,
163
+ referee_list[0] if referee_list else None,
164
+ ))
165
+
166
+ # -----------------------------------------------------------------------
167
+ # PlayerInMatch
168
+ # -----------------------------------------------------------------------
169
+ pim_rows = []
170
+ for team_name, player_list in info.get('players', {}).items():
171
+ for common_name in player_list:
172
+ player_id = pid(common_name)
173
+ if player_id:
174
+ pim_rows.append((match_id, player_id, team_name))
175
+ else:
176
+ logging.warning(
177
+ f"{filename}: player '{common_name}' not in registry — "
178
+ f"skipping PlayerInMatch row."
179
+ )
180
+ if pim_rows:
181
+ cursor.executemany(
182
+ "INSERT OR IGNORE INTO PlayerInMatch (match_id, player_id, team_name) "
183
+ "VALUES (?, ?, ?)",
184
+ pim_rows
185
+ )
186
+
187
+ # -----------------------------------------------------------------------
188
+ # Deliveries + FielderDismissals
189
+ # -----------------------------------------------------------------------
190
+ for inning_idx, inning_data in enumerate(data.get('innings', [])):
191
+ inning_number = inning_idx + 1 # 1–4 for Tests; no super-overs
192
+
193
+ batting_team = inning_data.get('team')
194
+ bowling_team = next(
195
+ (t for t in teams if t != batting_team),
196
+ 'Unknown'
197
+ )
198
+
199
+ for over_data in inning_data.get('overs', []):
200
+ over_num = over_data.get('over')
201
+ legal_ball_count = 0
202
+
203
+ for seq_idx, delivery in enumerate(over_data.get('deliveries', [])):
204
+ extras_info = delivery.get('extras', {})
205
+ wides = extras_info.get('wides', 0)
206
+ noballs = extras_info.get('noballs', 0)
207
+ byes = extras_info.get('byes', 0)
208
+ legbyes = extras_info.get('legbyes', 0)
209
+
210
+ # Only count legal deliveries towards ball_number
211
+ if wides == 0 and noballs == 0:
212
+ legal_ball_count += 1
213
+ ball_number = legal_ball_count
214
+
215
+ striker_id = pid(delivery.get('batter'))
216
+ non_striker_id = pid(delivery.get('non_striker'))
217
+ bowler_id = pid(delivery.get('bowler'))
218
+
219
+ if not all([striker_id, non_striker_id, bowler_id]):
220
+ missing = []
221
+ if not striker_id: missing.append(f"batter:'{delivery.get('batter')}'")
222
+ if not non_striker_id: missing.append(f"non_striker:'{delivery.get('non_striker')}'")
223
+ if not bowler_id: missing.append(f"bowler:'{delivery.get('bowler')}'")
224
+ logging.warning(
225
+ f"{filename} inn={inning_number} O{over_num} ball{seq_idx+1}: "
226
+ f"ID lookup failed for {', '.join(missing)} — skipping delivery."
227
+ )
228
+ continue
229
+
230
+ wicket_list = delivery.get('wickets') or []
231
+ wicket_info = wicket_list[0] if wicket_list else {}
232
+ player_out = wicket_info.get('player_out')
233
+ player_out_id = pid(player_out) if player_out else None
234
+ fielder_names = [
235
+ f.get('name') for f in wicket_info.get('fielders', [])
236
+ if f.get('name')
237
+ ]
238
+ fielder_ids = [pid(n) for n in fielder_names if pid(n)]
239
+
240
+ if player_out and not player_out_id:
241
+ logging.warning(
242
+ f"{filename}: player_out '{player_out}' ID not found — "
243
+ f"stored as NULL."
244
+ )
245
+ if len(fielder_names) != len(fielder_ids):
246
+ failed = [n for n in fielder_names if not pid(n)]
247
+ logging.warning(
248
+ f"{filename}: fielder ID lookup failed for {failed}."
249
+ )
250
+
251
+ try:
252
+ cursor.execute("""
253
+ INSERT INTO Deliveries (
254
+ match_id, inning, over_number, ball_number,
255
+ batting_team, bowling_team,
256
+ striker_id, non_striker_id, bowler_id,
257
+ runs_scored, extra_runs,
258
+ wides, noballs, byes, legbyes,
259
+ wicket_type, player_out_id
260
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
261
+ """, (
262
+ match_id, inning_number, over_num, ball_number,
263
+ batting_team, bowling_team,
264
+ striker_id, non_striker_id, bowler_id,
265
+ delivery.get('runs', {}).get('batter', 0),
266
+ delivery.get('runs', {}).get('extras', 0),
267
+ wides, noballs, byes, legbyes,
268
+ wicket_info.get('kind'),
269
+ player_out_id,
270
+ ))
271
+
272
+ if fielder_ids:
273
+ delivery_id = cursor.lastrowid
274
+ cursor.executemany(
275
+ "INSERT INTO FielderDismissals "
276
+ "(delivery_id, fielder_id) VALUES (?, ?)",
277
+ [(delivery_id, fid) for fid in fielder_ids]
278
+ )
279
+
280
+ except sqlite3.IntegrityError as e:
281
+ logging.error(
282
+ f"{filename} inn={inning_number} O{over_num} "
283
+ f"B{ball_number}: IntegrityError — {e} — skipping."
284
+ )
285
+
286
+
287
+ # ---------------------------------------------------------------------------
288
+ # Main
289
+ # ---------------------------------------------------------------------------
290
+ def main():
291
+ create_database()
292
+ start_time = time.time()
293
+
294
+ # ------------------------------------------------------------------
295
+ # Determine source: zip or directory
296
+ # ------------------------------------------------------------------
297
+ use_zip = os.path.exists(JSON_ZIP_PATH)
298
+ if use_zip:
299
+ zf = zipfile.ZipFile(JSON_ZIP_PATH, 'r')
300
+ filenames = sorted(
301
+ [n for n in zf.namelist() if n.endswith('.json')],
302
+ key=lambda x: int(os.path.splitext(x)[0])
303
+ )
304
+ print(f"Source: {JSON_ZIP_PATH} ({len(filenames)} JSON files)")
305
+ else:
306
+ if not os.path.isdir(JSON_DIR_PATH):
307
+ print(f"ERROR: neither {JSON_ZIP_PATH} nor {JSON_DIR_PATH} found.")
308
+ return
309
+ filenames = sorted(
310
+ [f for f in os.listdir(JSON_DIR_PATH) if f.endswith('.json')],
311
+ key=lambda x: int(os.path.splitext(x)[0])
312
+ )
313
+ print(f"Source: {JSON_DIR_PATH} ({len(filenames)} JSON files)")
314
+
315
+ total = len(filenames)
316
+ processed = 0
317
+ skipped = 0
318
+
319
+ db_conn = sqlite3.connect(DB_PATH)
320
+ db_conn.execute("PRAGMA foreign_keys = ON;")
321
+ db_conn.execute("PRAGMA journal_mode = WAL;") # faster bulk inserts
322
+ db_conn.execute("PRAGMA synchronous = NORMAL;")
323
+
324
+ for i, filename in enumerate(filenames):
325
+ base = os.path.basename(filename)
326
+ print(f"\r [{i+1:>4}/{total}] {base} (ok={processed} skip={skipped})", end='', flush=True)
327
+
328
+ try:
329
+ if use_zip:
330
+ content = zf.read(filename)
331
+ else:
332
+ with open(os.path.join(JSON_DIR_PATH, base), 'rb') as fh:
333
+ content = fh.read()
334
+
335
+ with db_conn: # transaction per file
336
+ process_file(db_conn, content, base)
337
+ processed += 1
338
+
339
+ except Exception as e:
340
+ logging.error(f"FAILED {base}: {e}")
341
+ skipped += 1
342
+
343
+ if use_zip:
344
+ zf.close()
345
+ db_conn.close()
346
+
347
+ elapsed = time.time() - start_time
348
+ print(f"\n\n{'='*60}")
349
+ print(f"Ingestion complete in {elapsed:.1f}s")
350
+ print(f" Processed : {processed}/{total}")
351
+ print(f" Skipped : {skipped}")
352
+ print(f" Database : {DB_PATH}")
353
+ print(f" Log : {LOG_PATH}")
354
+ print(f"{'='*60}")
355
+
356
+
357
+ if __name__ == '__main__':
358
+ main()
schema_tests.sql ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PRAGMA foreign_keys=OFF;
2
+
3
+ -- Players: universal, unchanged
4
+ CREATE TABLE IF NOT EXISTS Players (
5
+ player_id TEXT PRIMARY KEY,
6
+ player_name TEXT NOT NULL
7
+ );
8
+
9
+ -- Matches: adapted for Test cricket
10
+ -- * start_date / end_date replace single match_date
11
+ -- * series_name replaces stage (Tests belong to a named series)
12
+ -- * match_type_number tracks match number within a series
13
+ -- * gender and team_type added (international / male|female)
14
+ -- * result_type extended to cover 'runs', 'wickets', 'draw', 'tie', 'no result'
15
+ CREATE TABLE IF NOT EXISTS Matches (
16
+ match_id INTEGER PRIMARY KEY,
17
+ season TEXT NOT NULL,
18
+ start_date TEXT NOT NULL, -- first day of match
19
+ end_date TEXT, -- last day played
20
+ venue TEXT NOT NULL,
21
+ city TEXT,
22
+ series_name TEXT, -- e.g. "Border-Gavaskar Trophy"
23
+ match_type_number INTEGER, -- match number within the series
24
+ gender TEXT, -- 'male' | 'female'
25
+ team_type TEXT, -- 'international' | 'club'
26
+ team1 TEXT NOT NULL,
27
+ team2 TEXT NOT NULL,
28
+ toss_winner TEXT NOT NULL,
29
+ toss_decision TEXT NOT NULL,
30
+ match_winner TEXT, -- NULL for draws / no results
31
+ result_type TEXT, -- 'runs' | 'wickets' | 'draw' | 'tie' | 'no result'
32
+ result_margin INTEGER, -- NULL for draws / ties / no results
33
+ player_of_match_id TEXT,
34
+ umpire1 TEXT,
35
+ umpire2 TEXT,
36
+ tv_umpire TEXT,
37
+ match_referee TEXT,
38
+ FOREIGN KEY (player_of_match_id) REFERENCES Players (player_id)
39
+ );
40
+
41
+ -- Deliveries: unchanged structurally; inning 1-4 covers all Test innings
42
+ CREATE TABLE IF NOT EXISTS Deliveries (
43
+ delivery_id INTEGER PRIMARY KEY AUTOINCREMENT,
44
+ match_id INTEGER NOT NULL,
45
+ inning INTEGER NOT NULL, -- 1, 2, 3, or 4
46
+ over_number INTEGER NOT NULL,
47
+ ball_number INTEGER NOT NULL, -- legal ball number (1-6)
48
+ batting_team TEXT NOT NULL,
49
+ bowling_team TEXT NOT NULL,
50
+ striker_id TEXT NOT NULL,
51
+ non_striker_id TEXT NOT NULL,
52
+ bowler_id TEXT NOT NULL,
53
+ runs_scored INTEGER NOT NULL, -- runs off bat
54
+ extra_runs INTEGER NOT NULL, -- total extras this ball
55
+ wides INTEGER DEFAULT 0,
56
+ noballs INTEGER DEFAULT 0,
57
+ byes INTEGER DEFAULT 0,
58
+ legbyes INTEGER DEFAULT 0,
59
+ wicket_type TEXT,
60
+ player_out_id TEXT,
61
+ FOREIGN KEY (match_id) REFERENCES Matches (match_id),
62
+ FOREIGN KEY (striker_id) REFERENCES Players (player_id),
63
+ FOREIGN KEY (non_striker_id) REFERENCES Players (player_id),
64
+ FOREIGN KEY (bowler_id) REFERENCES Players (player_id),
65
+ FOREIGN KEY (player_out_id) REFERENCES Players (player_id)
66
+ );
67
+
68
+ -- Playing XI per match
69
+ CREATE TABLE IF NOT EXISTS PlayerInMatch (
70
+ match_id INTEGER NOT NULL,
71
+ player_id TEXT NOT NULL,
72
+ team_name TEXT NOT NULL,
73
+ PRIMARY KEY (match_id, player_id),
74
+ FOREIGN KEY (match_id) REFERENCES Matches (match_id),
75
+ FOREIGN KEY (player_id) REFERENCES Players (player_id)
76
+ );
77
+
78
+ -- Fielder dismissals (caught, run-out, stumped, etc.)
79
+ CREATE TABLE IF NOT EXISTS FielderDismissals (
80
+ fielder_dismissal_id INTEGER PRIMARY KEY AUTOINCREMENT,
81
+ delivery_id INTEGER NOT NULL,
82
+ fielder_id TEXT NOT NULL,
83
+ FOREIGN KEY (delivery_id) REFERENCES Deliveries (delivery_id),
84
+ FOREIGN KEY (fielder_id) REFERENCES Players (player_id)
85
+ );
86
+
87
+ PRAGMA foreign_keys=ON;
tests.db ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f261ce7725f8f44467d7ffa609ef64008c694ad1382d9fa0ac721933cf806cf0
3
+ size 129159168