-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2682 lines (2175 loc) · 101 KB
/
Copy pathapp.py
File metadata and controls
2682 lines (2175 loc) · 101 KB
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Instagram Follower Scraper API
A Flask API that provides functionality to scrape Instagram followers from specified accounts,
detect their gender, filter them based on gender preferences, and persist to Supabase.
REFACTORED FOR PRODUCTION:
- Asynchronous task processing with Celery
- Background workers for scalability
- Batch operations for memory efficiency
- Logging and error tracking with Sentry
- Rate limiting for API protection
"""
from flask import Flask, request, jsonify
from flask_cors import CORS
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import os
import logging
import threading
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.celery import CeleryIntegration
from dotenv import load_dotenv
from apify_client import ApifyClient
import pandas as pd
import gender_guesser.detector as gender
import re
from typing import Optional, List, Dict, Any
from supabase import create_client, Client
from supabase.lib.client_options import ClientOptions
from datetime import datetime, timezone, date, timedelta
import uuid
import random
import time
from pyairtable import Api
import traceback
# Import utility modules
from utils.airtable_creator import AirtableCreator, create_airtable_base
from utils.base_id_utils import get_base_id_from_request, ensure_base_id, ensure_base_id_list, validate_base_id, get_va_table_count
from utils.rls_context import set_rls_context, get_rls_context
# Load environment variables from .env file
load_dotenv()
# ===================================================================
# LOGGING CONFIGURATION
# ===================================================================
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
# ===================================================================
# SENTRY ERROR TRACKING
# ===================================================================
if os.getenv('SENTRY_DSN'):
sentry_sdk.init(
dsn=os.getenv('SENTRY_DSN'),
integrations=[
FlaskIntegration(),
CeleryIntegration()
],
traces_sample_rate=0.1, # 10% performance monitoring
environment=os.getenv('FLASK_ENV', 'development'),
release=os.getenv('APP_VERSION', '1.0.0')
)
logger.info("Sentry error tracking initialized")
else:
logger.warning("SENTRY_DSN not set, error tracking disabled")
# Constants
DEFAULT_PROFILES_PER_TABLE = 180 # Fallback if client doesn't send value
# ===================================================================
# FLASK APP INITIALIZATION
# ===================================================================
app = Flask(__name__)
# CORS configuration with restricted origins
allowed_origins = os.getenv('ALLOWED_ORIGINS', '*').split(',')
CORS(app, resources={
r"/api/*": {
"origins": allowed_origins,
"methods": ["GET", "POST"],
"allow_headers": ["Content-Type", "X-API-Key", "X-Base-Id"]
}
})
# Rate limiting configuration
# Use in-memory storage to avoid SSL issues with Redis for rate limiting
limiter = Limiter(
app=app,
key_func=get_remote_address,
default_limits=["200 per hour"],
storage_uri='memory://' # Use in-memory storage instead of Redis
)
logger.info("Flask app initialized with CORS and rate limiting")
# ===================================================================
# RLS CONTEXT SETUP
# ===================================================================
# Initialize RLS context on every request with the base_id
# This allows Supabase RLS policies to filter data per tenant
@app.before_request
def setup_rls_context():
"""
Set up RLS context for the current request.
Extracts base_id from request headers/body and sets it in the RLS context,
which is then used by Supabase RLS policies to filter data per tenant.
Skips RLS setup for:
- OPTIONS requests (CORS preflight)
- Health check endpoints (/, /health)
- Static file requests
"""
# Skip RLS setup for OPTIONS requests (CORS preflight)
if request.method == 'OPTIONS':
return
# Skip RLS setup for health check and root endpoints
if request.path in ['/', '/health', '/favicon.ico']:
return
try:
# Extract base_id from request (uses priority: header > body)
# required=False allows requests without base_id to proceed
# Individual endpoints can validate if they need it
base_id = get_base_id_from_request(required=False)
# Only set RLS context if base_id is provided
if base_id:
# Validate base_id format
if not validate_base_id(base_id):
logger.warning(f"Invalid base_id format in request: {base_id}")
# Still set it (validation error will be caught later in endpoint)
# Set RLS context for this request
set_rls_context(base_id)
logger.debug(f"RLS context initialized for base_id={base_id}")
else:
logger.debug(f"No base_id provided for {request.method} {request.path}")
except Exception as e:
logger.error(f"Error setting up RLS context: {e}")
# Continue without RLS context - individual endpoints will validate if needed
logger.info("✓ RLS context setup enabled for multi-tenant isolation")
# ===================================================================
# SUPABASE CLIENT WITH CONNECTION POOLING (THREAD-SAFE)
# ===================================================================
# Use singleton pattern with thread lock to prevent race conditions in multi-threaded Flask
_supabase_client = None
_supabase_lock = threading.Lock()
def get_supabase_client() -> Client:
"""
Initialize and return Supabase client using service role key.
OPTIMIZED FOR 500K+ SCALE:
- Thread-safe singleton pattern to reuse the same client instance
- Connection pooling with limits to prevent pool exhaustion
- Configurable pool size via environment variable
- Automatic connection cleanup and recycling
"""
global _supabase_client
# Double-checked locking pattern for thread safety
if _supabase_client is not None:
return _supabase_client
with _supabase_lock:
# Check again inside lock (another thread might have initialized it)
if _supabase_client is not None:
return _supabase_client
# Initialize new client
supabase_url = os.getenv('SUPABASE_URL')
supabase_key = os.getenv('SUPABASE_SERVICE_ROLE_KEY')
if not supabase_url or not supabase_key:
raise ValueError("SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY environment variables are required.")
# Configure connection pooling for scale
# Free Tier: Max 50 connections total across all clients
# Render Free: 1 web worker + 1 celery worker = need conservative pool
# Default: 5 connections per process (safe for free tier)
# Pro tier: Increase to 20-30
pool_size = int(os.getenv('SUPABASE_POOL_SIZE', '5'))
# Create client options with proper ClientOptions object
options = ClientOptions(
schema='public',
headers={
'x-client-info': 'instagram-scraper-api/1.0'
},
auto_refresh_token=False,
persist_session=False
)
_supabase_client = create_client(
supabase_url,
supabase_key,
options=options
)
logger.info(f"✓ Supabase client initialized with connection pool (size: {pool_size}, tier: free)")
return _supabase_client
def get_airtable_client() -> Api:
"""
Initialize and return Airtable API client.
Returns:
Airtable API client instance
"""
airtable_token = os.getenv('AIRTABLE_ACCESS_TOKEN')
if not airtable_token:
raise ValueError("AIRTABLE_ACCESS_TOKEN environment variable is required.")
return Api(airtable_token)
def scrape_followers(accounts: list, max_count: int = 5, platform: str = 'instagram') -> dict:
"""
Wrapper function that delegates to the utility scraper module.
Args:
accounts: A list of account usernames to scrape followers from.
max_count: Maximum followers to scrape per account (default: 5).
platform: Platform to scrape ('instagram', 'tiktok', 'threads', 'x'). Defaults to 'instagram'.
Returns:
A dictionary mapping each account to their extracted followers data.
Each follower entry contains username, full_name, follower_count, following_count, posts_count.
"""
# Import and use the utility scraper function which has all the platform-specific logic
from utils.scraper import scrape_followers as scraper_scrape_followers
return scraper_scrape_followers(accounts, max_count, platform=platform)
def detect_gender(followers: dict) -> dict:
"""
Performs gender detection on the scraped followers.
Args:
followers: Dictionary of followers with their profile information.
Returns:
Dictionary mapping each follower username to their detected gender
("male", "female", or "unknown").
"""
# Initialize the gender detector
detector = gender.Detector(case_sensitive=False)
def extract_names(text: str) -> List[str]:
"""Extract potential names from text, handling various formats."""
if not text:
return []
# Remove common prefixes and suffixes
cleaned = re.sub(r'(^(mrs?|ms|dr|prof|sir|lady|miss)\.?\s+)|(\d+|_+|\.+)',
'', text, flags=re.IGNORECASE)
# Split by common separators and extract alphabetic sequences
parts = re.split(r'[_\.\-\s\d]+', cleaned)
names = []
for part in parts:
# Extract alphabetic sequences of reasonable length (2-20 chars)
name_matches = re.findall(r'[A-Za-z]{2,20}', part)
names.extend(name_matches)
# Exclude common non-name words but keep gender-indicating titles
excluded_words = {
'the', 'and', 'official', 'real', 'true', 'page', 'account', 'profile',
'fitness', 'gym', 'workout', 'life', 'love', 'style', 'blog', 'shop'
}
return [name for name in names if name.lower() not in excluded_words and len(name) >= 2]
def check_gender_keywords(text: str) -> str:
"""Check for gender-indicating keywords in text."""
if not text:
return 'unknown'
text_lower = text.lower()
# Male-indicating words
male_keywords = ['king', 'prince', 'sir', 'mr', 'lord', 'duke']
# Female-indicating words
female_keywords = ['queen', 'princess', 'lady', 'mrs', 'ms', 'miss', 'duchess']
for keyword in male_keywords:
if keyword in text_lower:
return 'male'
for keyword in female_keywords:
if keyword in text_lower:
return 'female'
return 'unknown'
def classify_gender(gender_result: str) -> str:
"""Classify gender_guesser results into male/female/unknown."""
if gender_result in ['male', 'mostly_male']:
return 'male'
elif gender_result in ['female', 'mostly_female']:
return 'female'
else:
return 'unknown'
def guess_gender_robust(username: str, full_name: Optional[str] = None) -> str:
"""
Robust gender detection function that tries multiple strategies.
Args:
username: Instagram username
full_name: Full name from profile (optional)
Returns:
'male', 'female', or 'unknown'
"""
# Strategy 1: Check for gender keywords first (in both username and full_name)
for text in [full_name, username]:
keyword_result = check_gender_keywords(text)
if keyword_result != 'unknown':
return keyword_result
# Strategy 2: Try full_name with name detection
if full_name:
names = extract_names(full_name)
for name in names:
result = detector.get_gender(name)
classified = classify_gender(result)
if classified != 'unknown':
return classified
# Strategy 3: Try username with name detection
if username:
names = extract_names(username)
for name in names:
result = detector.get_gender(name)
classified = classify_gender(result)
if classified != 'unknown':
return classified
return 'unknown'
# Apply gender detection to all followers
followers_gender = {}
for username, follower_data in followers.items():
detected_gender = guess_gender_robust(
username,
follower_data.get('full_name', '')
)
followers_gender[username] = detected_gender
return followers_gender
def filter_by_gender(followers_gender: dict, target_gender: str) -> dict:
"""
Filters followers based on the specified gender.
Args:
followers_gender: Dictionary mapping follower usernames to their detected gender.
target_gender: Target gender to filter for ("male" or "female").
Returns:
Dictionary of filtered followers according to gender rules:
- If target_gender="male", returns "male" + "unknown"
- If target_gender="female", returns "female" + "unknown"
"""
filtered_followers = {}
if target_gender.lower() == "male":
# Include male and unknown gender followers
for username, gender in followers_gender.items():
if gender in ["male", "unknown"]:
filtered_followers[username] = gender
elif target_gender.lower() == "female":
# Include female and unknown gender followers
for username, gender in followers_gender.items():
if gender in ["female", "unknown"]:
filtered_followers[username] = gender
else:
# Invalid target_gender, return empty dict
print(f"Warning: Invalid target_gender '{target_gender}'. Must be 'male' or 'female'.")
return {}
return filtered_followers
def process_accounts(accounts: list, target_gender: str = "male", max_count_per_account: int = 5, platform: str = "instagram") -> dict:
"""
Orchestrates the entire workflow.
Args:
accounts: List of social media usernames to scrape followers from.
target_gender: Target gender to filter for ("male" or "female").
max_count_per_account: Maximum followers to scrape per account.
platform: Social media platform to scrape from (default: "instagram").
Returns:
Dictionary with filtered followers data and summary statistics.
"""
platform_name = platform.capitalize()
print(f"Starting {platform_name} follower analysis for accounts: {accounts}")
print(f"Target gender: {target_gender}")
print(f"Max count per account: {max_count_per_account}")
# Step 1: Scrape followers from specified accounts
print("\n1. Scraping followers...")
followers = scrape_followers(accounts, max_count_per_account, platform=platform)
print(f" Scraped {len(followers)} total followers")
# Step 2: Detect gender for all followers
print("\n2. Detecting gender...")
followers_gender = detect_gender(followers)
# Display gender distribution
gender_counts = {}
for gender in followers_gender.values():
gender_counts[gender] = gender_counts.get(gender, 0) + 1
print(" Gender distribution:")
for gender, count in gender_counts.items():
print(f" {gender}: {count}")
# Step 3: Filter followers by target gender
print(f"\n3. Filtering by target gender '{target_gender}'...")
filtered_followers = filter_by_gender(followers_gender, target_gender)
print(f" Filtered results: {len(filtered_followers)} followers")
# Create complete follower data with gender information
complete_follower_data = []
for username in filtered_followers.keys():
follower_info = followers.get(username, {})
complete_follower_data.append({
'id': follower_info.get('id', username), # Use ID or fallback to username
'fullName': follower_info.get('full_name', ''),
'username': username,
})
return {
'accounts': complete_follower_data,
'totalFiltered': len(complete_follower_data),
'totalScraped': len(followers),
'genderDistribution': gender_counts
}
# ============================================================================
# HEALTH CHECK ENDPOINTS (no base_id required)
# ============================================================================
@app.route('/', methods=['GET'])
def root():
"""
Root endpoint for basic health checks and uptime monitoring.
Does not require base_id authentication.
"""
return jsonify({
'status': 'ok',
'service': 'Instagram Scraper API',
'version': '1.0.0'
}), 200
# ============================================================================
# API ENDPOINTS (base_id required via before_request handler)
# ============================================================================
@app.route('/api/scrape-followers', methods=['POST'])
def scrape_followers_api():
"""
API endpoint to scrape Instagram followers.
Expected JSON payload:
{
"accounts": ["username1", "username2"],
"targetGender": "male" (optional, defaults to "male"),
"totalScrapeCount": 150 (optional, total accounts to scrape across all usernames)
}
Returns:
{
"success": true,
"data": {
"accounts": [
{
"id": "account_id",
"fullName": "Full Name",
"username": "username"
}
],
"totalFiltered": 10,
"totalScraped": 15,
"genderDistribution": {
"male": 8,
"female": 4,
"unknown": 3
}
}
}
"""
try:
# Get JSON data from request
data = request.get_json()
if not data or 'accounts' not in data:
return jsonify({
'success': False,
'error': 'Missing "accounts" field in request body'
}), 400
accounts = data['accounts']
target_gender = data.get('targetGender', 'male') # Default to male
total_scrape_count = data.get('totalScrapeCount', None) # User-defined total count
platform = data.get('platform', 'instagram') # Default to instagram
if not isinstance(accounts, list) or len(accounts) == 0:
return jsonify({
'success': False,
'error': 'Accounts must be a non-empty list'
}), 400
# Compute per-account scrape count
if total_scrape_count is not None:
if total_scrape_count <= 0:
return jsonify({
'success': False,
'error': 'totalScrapeCount must be greater than 0'
}), 400
# Compute how many accounts to scrape per username
per_account_count = int(total_scrape_count / len(accounts))
if per_account_count == 0:
return jsonify({
'success': False,
'error': f'totalScrapeCount ({total_scrape_count}) is too small for {len(accounts)} accounts. Need at least {len(accounts)} total.'
}), 400
print(f"Total scrape count: {total_scrape_count}")
print(f"Number of accounts: {len(accounts)}")
print(f"Per-account count: {per_account_count}")
else:
# Fallback to default if not provided
per_account_count = 5
print(f"No totalScrapeCount provided, using default per-account count: {per_account_count}")
# Process the accounts with computed per-account count and platform
result = process_accounts(accounts, target_gender, per_account_count, platform)
return jsonify({
'success': True,
'data': result
})
return jsonify({
'success': True,
'data': result
})
except Exception as e:
print(f"Error processing request: {str(e)}")
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/ingest', methods=['POST'])
def ingest_profiles():
"""
API endpoint to ingest scraped profiles into Supabase.
This endpoint is idempotent: calling it multiple times with the same profiles
will not create duplicates in global_usernames.
Expected JSON payload:
{
"profiles": [
{
"id": "123456",
"username": "john_doe",
"full_name": "John Doe"
}
],
"base_id": "appXYZ123ABC" (optional, defaults to 'default_instagram')
}
OR pass base_id via header:
X-Base-Id: appXYZ123ABC
Returns:
{
"success": true,
"base_id": "appXYZ123ABC",
"inserted_raw": 10,
"added_to_global": 8,
"skipped_existing": 2
}
"""
try:
# Get JSON data from request
data = request.get_json()
if not data or 'profiles' not in data:
return jsonify({
'success': False,
'error': 'Missing "profiles" field in request body'
}), 400
profiles = data['profiles']
if not isinstance(profiles, list):
return jsonify({
'success': False,
'error': 'Profiles must be a list'
}), 400
if len(profiles) == 0:
return jsonify({
'success': True,
'base_id': get_base_id_from_request(),
'inserted_raw': 0,
'added_to_global': 0,
'skipped_existing': 0
})
# Extract base_id with fallback to default
base_id = get_base_id_from_request()
if not validate_base_id(base_id):
return jsonify({
'success': False,
'error': f'Invalid base_id format: {base_id}'
}), 400
# Initialize Supabase client
supabase = get_supabase_client()
# Counters for response
inserted_raw = 0
added_to_global = 0
skipped_existing = 0
logger.info(f"Ingesting {len(profiles)} profiles for base_id={base_id}")
# Process each profile
for profile in profiles:
# Validate required fields
if 'id' not in profile or 'username' not in profile:
print(f"Warning: Skipping profile with missing id or username: {profile}")
continue
profile_id = str(profile['id'])
username = profile['username']
full_name = profile.get('full_name', '')
# Step 1: Insert into raw_scraped_profiles with base_id
try:
supabase.table('raw_scraped_profiles').insert({
'id': profile_id,
'username': username,
'full_name': full_name,
'base_id': base_id,
'scraped_at': datetime.now(timezone.utc).isoformat()
}).execute()
inserted_raw += 1
print(f"✓ Inserted {username} into raw_scraped_profiles (base_id={base_id})")
except Exception as e:
print(f"Warning: Failed to insert {username} into raw_scraped_profiles: {str(e)}")
# Step 2: Check if profile exists in global_usernames (scoped to base_id)
try:
existing = supabase.table('global_usernames')\
.select('id')\
.eq('id', profile_id)\
.eq('base_id', base_id)\
.execute()
if existing.data and len(existing.data) > 0:
# Profile already exists in global_usernames for this base_id
skipped_existing += 1
print(f"○ Skipped {username} (already in global_usernames for base_id={base_id})")
else:
# Profile doesn't exist for this base_id, insert it
supabase.table('global_usernames').insert({
'id': profile_id,
'username': username,
'full_name': full_name,
'used': False,
'base_id': base_id,
'created_at': datetime.now(timezone.utc).isoformat()
}).execute()
added_to_global += 1
print(f"✓ Added {username} to global_usernames (base_id={base_id})")
except Exception as e:
print(f"Warning: Failed to process {username} for global_usernames: {str(e)}")
skipped_existing += 1
logger.info(f"Ingest complete for base_id={base_id}: {inserted_raw} raw, {added_to_global} new global, {skipped_existing} skipped")
return jsonify({
'success': True,
'base_id': base_id,
'inserted_raw': inserted_raw,
'added_to_global': added_to_global,
'skipped_existing': skipped_existing
})
except Exception as e:
print(f"Error processing ingest request: {str(e)}")
import traceback
traceback.print_exc()
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/daily-selection', methods=['POST'])
def daily_selection():
"""
API endpoint to select fresh profiles for a new campaign.
Creates a new campaign and selects up to (NUM_VA_TABLES * profiles_per_table) unused profiles
from global_usernames, marking them as used.
Expected JSON payload:
{
"campaign_date": "2025-10-02" (optional, defaults to today),
"profiles_per_table": 180 (optional, should be sent from client's NEXT_PUBLIC_PROFILES_PER_TABLE),
"base_id": "appXYZ123ABC" (optional, defaults to 'default_instagram')
}
OR pass base_id via header:
X-Base-Id: appXYZ123ABC
Returns:
{
"success": true,
"campaign_id": "uuid",
"base_id": "appXYZ123ABC",
"total_selected": 14400
}
"""
try:
# Get JSON data from request
data = request.get_json() or {}
# Extract base_id with fallback to default
base_id = get_base_id_from_request()
if not validate_base_id(base_id):
return jsonify({
'success': False,
'error': f'Invalid base_id format: {base_id}'
}), 400
# Get profiles_per_table from client (should be NEXT_PUBLIC_PROFILES_PER_TABLE)
profiles_per_table = data.get('profiles_per_table')
if profiles_per_table is not None:
profiles_per_table = int(profiles_per_table)
# Validate
if profiles_per_table <= 0:
return jsonify({
'success': False,
'error': 'profiles_per_table must be a positive integer'
}), 400
print(f"✓ Using profiles_per_table from client: {profiles_per_table}")
else:
profiles_per_table = DEFAULT_PROFILES_PER_TABLE
print(f"⚠️ WARNING: Client did not send profiles_per_table, using fallback: {profiles_per_table}")
# Initialize Supabase client
supabase = get_supabase_client()
# Get number of VA tables dynamically from database/Airtable
airtable_token = os.getenv('AIRTABLE_ACCESS_TOKEN')
num_va_tables = get_va_table_count(base_id, supabase, airtable_token)
# Calculate target count: num_va_tables * profiles_per_table
target_count = num_va_tables * profiles_per_table
# Get campaign date (default to today)
campaign_date_str = data.get('campaign_date')
if campaign_date_str:
campaign_date_obj = datetime.strptime(campaign_date_str, '%Y-%m-%d').date()
else:
campaign_date_obj = date.today()
print(f"Starting daily selection for {campaign_date_obj} with base_id={base_id}...")
print(f"Target: {target_count} profiles ({num_va_tables} VA tables × {profiles_per_table} profiles/table)")
# Step 1: Create a new campaign with base_id
campaign_id = str(uuid.uuid4())
campaign_response = supabase.table('campaigns').insert({
'campaign_id': campaign_id,
'campaign_date': campaign_date_obj.isoformat(),
'total_assigned': 0,
'base_id': base_id,
'airtable_base_id': base_id, # Store the Airtable base ID (same as base_id)
'status': False, # Default to False (failed), will update to True (success) after Airtable sync
'created_at': datetime.now(timezone.utc).isoformat()
}).execute()
print(f"✓ Created campaign: {campaign_id} (base_id={base_id})")
# Step 2: Select up to target_count unused profiles from global_usernames
# Scoped to the specific base_id
available_profiles = supabase.table('global_usernames')\
.select('id, username, full_name')\
.eq('used', False)\
.eq('base_id', base_id)\
.limit(target_count)\
.execute()
if not available_profiles.data:
return jsonify({
'success': False,
'error': f'No unused profiles available in global_usernames for base_id={base_id}'
}), 400
selected_profiles = available_profiles.data
total_selected = len(selected_profiles)
print(f"✓ Selected {total_selected} unused profiles from base_id={base_id}")
# Step 3: Mark selected profiles as used
profile_ids = [profile['id'] for profile in selected_profiles]
# Update all selected profiles to used=true (scoped to base_id)
for profile_id in profile_ids:
supabase.table('global_usernames')\
.update({
'used': True,
'used_at': datetime.now(timezone.utc).isoformat()
})\
.eq('id', profile_id)\
.eq('base_id', base_id)\
.execute()
print(f"✓ Marked {total_selected} profiles as used for base_id={base_id}")
# Step 4: Insert into daily_assignments with placeholders and base_id
assignments = []
for profile in selected_profiles:
assignments.append({
'assignment_id': str(uuid.uuid4()),
'campaign_id': campaign_id,
'va_table_number': 0, # Placeholder - will be assigned during distribution
'position': 0, # Placeholder - will be assigned during distribution
'id': profile['id'],
'username': profile['username'],
'full_name': profile['full_name'],
'base_id': base_id,
'status': 'pending',
'assigned_at': datetime.now(timezone.utc).isoformat()
})
# Batch insert assignments (Supabase handles this efficiently)
supabase.table('daily_assignments').insert(assignments).execute()
print(f"✓ Inserted {total_selected} assignments for base_id={base_id}")
# Step 5: Update campaign total_assigned
supabase.table('campaigns')\
.update({'total_assigned': total_selected})\
.eq('campaign_id', campaign_id)\
.execute()
print(f"✓ Updated campaign total_assigned to {total_selected}")
logger.info(f"Daily selection complete for base_id={base_id}: campaign_id={campaign_id}, total_selected={total_selected}")
return jsonify({
'success': True,
'campaign_id': campaign_id,
'base_id': base_id,
'total_selected': total_selected,
'campaign_date': campaign_date_obj.isoformat()
})
except Exception as e:
print(f"Error processing daily selection request: {str(e)}")
import traceback
traceback.print_exc()
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route('/api/distribute/<campaign_id>', methods=['POST'])
def distribute_campaign(campaign_id: str):
"""
API endpoint to distribute campaign profiles to VA tables.
Fetches all unassigned profiles for a campaign, shuffles them randomly,
and assigns them to VA tables with positions.
URL Parameters:
campaign_id: UUID of the campaign to distribute
Optional JSON payload:
{
"profiles_per_table": 180, (optional, should be sent from client's NEXT_PUBLIC_PROFILES_PER_TABLE)
"base_id": "appXYZ123ABC" (optional, defaults to 'default_instagram')
}
OR pass base_id via header:
X-Base-Id: appXYZ123ABC
Returns:
{
"success": true,
"campaign_id": "uuid",
"base_id": "appXYZ123ABC",
"va_tables": 80,
"assigned_per_table": 180,
"total_distributed": 14400
}
"""
try:
# Extract base_id with fallback to default
base_id = get_base_id_from_request()
if not validate_base_id(base_id):
return jsonify({
'success': False,
'error': f'Invalid base_id format: {base_id}'
}), 400
# Initialize Supabase client
supabase = get_supabase_client()
# Get number of VA tables dynamically from database/Airtable
airtable_token = os.getenv('AIRTABLE_ACCESS_TOKEN')
num_va_tables = get_va_table_count(base_id, supabase, airtable_token)
# Get profiles_per_table from request body (should be from client's NEXT_PUBLIC_PROFILES_PER_TABLE)
data = request.get_json() or {}
profiles_per_table = data.get('profiles_per_table')
if profiles_per_table is not None:
profiles_per_table = int(profiles_per_table)
# Validate
if profiles_per_table <= 0:
return jsonify({
'success': False,
'error': 'profiles_per_table must be a positive integer'
}), 400
print(f"✓ Using profiles_per_table from client: {profiles_per_table}")
else:
profiles_per_table = DEFAULT_PROFILES_PER_TABLE
print(f"⚠️ WARNING: Client did not send profiles_per_table, using fallback: {profiles_per_table}")
print(f"Starting distribution for campaign {campaign_id} with base_id={base_id}...")
print(f"Configuration: {num_va_tables} VA tables (dynamic), {profiles_per_table} profiles per table")
# Step 1: Verify campaign exists (scoped to base_id)
campaign = supabase.table('campaigns')\
.select('campaign_id, campaign_date, total_assigned, base_id')\
.eq('campaign_id', campaign_id)\
.eq('base_id', base_id)\
.execute()
if not campaign.data or len(campaign.data) == 0:
return jsonify({
'success': False,
'error': f'Campaign {campaign_id} not found for base_id={base_id}'
}), 404
campaign_info = campaign.data[0]
print(f"✓ Found campaign: {campaign_info['campaign_date']} with {campaign_info['total_assigned']} assignments")