Skip to content

Commit 3a7acec

Browse files
committed
fix: include more films in recent_updates
1 parent c5519aa commit 3a7acec

1 file changed

Lines changed: 37 additions & 50 deletions

File tree

scripts/data_import.py

Lines changed: 37 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -240,65 +240,51 @@ def import_to_d1(batch_files, db_mode='local', db_name=None):
240240

241241
return True
242242

243-
def generate_recent_updates(repo_dir, output_json_path="static/recent_updates.json", limit=20):
244-
"""Generate recent updates JSON from git diff."""
245-
print("Generating recent updates from git diff...")
243+
def generate_recent_updates(repo_dir, output_json_path="static/recent_updates.json", limit=100, days=21):
244+
"""Generate recent updates JSON from films certified in the past X days."""
245+
print(f"Generating recent updates from past {days} days...")
246246

247247
try:
248-
# Get the diff of the last commit for data/data.csv
249-
result = subprocess.run(
250-
['git', 'log', '-1', '-p', '--', 'data/data.csv'],
251-
cwd=repo_dir,
252-
capture_output=True,
253-
text=True,
254-
check=True
255-
)
256-
diff_output = result.stdout
257-
258-
new_lines = []
259-
for line in diff_output.splitlines():
260-
if line.startswith('+') and not line.startswith('+++'):
261-
content = line[1:]
262-
if content.startswith('id,certificate_id') or content.startswith('id,movie_name'):
263-
continue
264-
if content.strip():
265-
new_lines.append(content)
266-
267-
if not new_lines:
268-
print("No new lines found in the last commit.")
269-
return
248+
from datetime import datetime, timedelta
270249

271-
print(f"Found {len(new_lines)} new lines.")
250+
# Calculate cutoff date
251+
cutoff_date = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
252+
print(f"Cutoff date: {cutoff_date}")
272253

273-
# Parse CSV lines
254+
# Read the full CSV
274255
data_csv_path = os.path.join(repo_dir, 'data', 'data.csv')
275-
with open(data_csv_path, 'r') as f:
276-
header_line = f.readline().strip()
277256

278-
header = header_line.split(',')
257+
if not os.path.exists(data_csv_path):
258+
print(f"CSV file not found: {data_csv_path}")
259+
return
279260

280-
csv_io = io.StringIO("\n".join(new_lines))
281-
reader = csv.reader(csv_io)
261+
with open(data_csv_path, 'r') as f:
262+
reader = csv.DictReader(f)
282263

283-
new_films = []
284-
seen_ids = set()
285-
for row in reader:
286-
if len(row) == len(header):
287-
film_data = dict(zip(header, row))
288-
film_id = film_data.get('id')
264+
new_films = []
265+
seen_ids = set()
289266

290-
if film_id and film_id not in seen_ids:
267+
for row in reader:
268+
cert_date = row.get('cert_date', '')
269+
film_id = row.get('id')
270+
271+
# Filter by cert_date (only films from past X days)
272+
if cert_date and cert_date >= cutoff_date and film_id and film_id not in seen_ids:
291273
# Clean name
292-
film_data['movie_name'] = clean_name(film_data.get('movie_name', ''))
274+
row['movie_name'] = clean_name(row.get('movie_name', ''))
293275
# Extract year
294-
year = extract_year(film_data.get('cert_date'), film_data.get('cert_no'))
295-
film_data['year'] = year
276+
year = extract_year(row.get('cert_date'), row.get('cert_no'))
277+
row['year'] = year
296278
# Generate slug
297-
film_data['slug'] = make_slug(film_data['movie_name'], year)
298-
new_films.append(film_data)
279+
row['slug'] = make_slug(row['movie_name'], year)
280+
new_films.append(row)
299281
seen_ids.add(film_id)
300282

301-
# Sort by cert_date descending
283+
print(f"Found {len(new_films)} films certified since {cutoff_date}")
284+
285+
if not new_films:
286+
print("No recent films found.")
287+
return
302288

303289
# Sort initially by date to ensure we pick latest from each language
304290
def get_date(x):
@@ -492,7 +478,7 @@ def generate_rss_feed(films, output_path="static/rss.xml"):
492478
except Exception as e:
493479
print(f"Error saving RSS feed: {e}")
494480

495-
def fetch_remote_data(output_path="src/lib/data/data.csv", limit=50):
481+
def fetch_remote_data(output_path="src/lib/data/data.csv", limit=100):
496482
"""Fetch latest data from remote source by cloning the repo."""
497483
os.makedirs(os.path.dirname(output_path), exist_ok=True)
498484

@@ -501,16 +487,16 @@ def fetch_remote_data(output_path="src/lib/data/data.csv", limit=50):
501487
with tempfile.TemporaryDirectory() as temp_dir:
502488
print(f"Cloning {repo_url}...")
503489
try:
504-
# Clone with depth 2 to ensure we have at least one parent for diff if needed,
505-
subprocess.run(['git', 'clone', '--depth', '2', repo_url, temp_dir], check=True)
490+
# Clone full repo to access all data (not just recent commits)
491+
subprocess.run(['git', 'clone', repo_url, temp_dir], check=True)
506492

507493
# Copy data.csv
508494
source_csv = os.path.join(temp_dir, 'data', 'data.csv')
509495
if os.path.exists(source_csv):
510496
shutil.copy2(source_csv, output_path)
511497
print(f"Data copied to {output_path}")
512498

513-
# Generate recent updates
499+
# Generate recent updates (past 21 days)
514500
generate_recent_updates(temp_dir, limit=limit)
515501

516502
return output_path
@@ -531,7 +517,8 @@ def main():
531517
parser.add_argument('--batch-size', type=int, default=DEFAULT_BATCH_SIZE, help='Batch size')
532518
parser.add_argument('--db-mode', choices=['local', 'remote'], default='local', help='Database mode')
533519
parser.add_argument('--fetch', action='store_true', help='Fetch data from remote source')
534-
parser.add_argument('--limit', type=int, default=20, help='Number of recent updates to track')
520+
parser.add_argument('--limit', type=int, default=100, help='Maximum number of recent updates to include in JSON')
521+
parser.add_argument('--days', type=int, default=21, help='Number of days to look back for recent updates')
535522

536523
args = parser.parse_args()
537524

0 commit comments

Comments
 (0)