-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgemini-ai-filter.php
More file actions
1680 lines (1588 loc) · 67.5 KB
/
Copy pathgemini-ai-filter.php
File metadata and controls
1680 lines (1588 loc) · 67.5 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
<?php
declare(strict_types=1);
require_once __DIR__ . '/lib/RssLeads/AiState.php';
require_once __DIR__ . '/lib/RssLeads/Priority.php';
require_once __DIR__ . '/lib/GeminiClient.php';
$user = getenv('RSS_LEADS_USER') ?: (getenv('FRESHRSS_USER') ?: 'invictine');
$dbPath = getenv('FRESHRSS_DB') ?: "/var/www/FreshRSS/data/users/{$user}/db.sqlite";
$apiKey = getenv('GEMINI_API_KEY') ?: '';
$gemmaModel = normalize_model_id(getenv('AI_GEMMA_MODEL') ?: 'gemma4-31b');
$refineModels = array_values(array_unique(array_filter(array_map(
static fn(string $model): string => normalize_model_id($model),
array_map('trim', explode(',', getenv('AI_REFINE_MODELS') ?: (getenv('GEMINI_MODELS') ?: 'gemini-3.1-flash-lite,gemini-3-flash')))
))));
$models = array_values(array_unique(array_merge($refineModels, [$gemmaModel])));
$allowModelFallbacks = in_array(strtolower((string)(getenv('AI_FILTER_ALLOW_MODEL_FALLBACKS') ?: '1')), ['1', 'true', 'yes'], true);
if (!$allowModelFallbacks && !empty($refineModels)) {
$refineModels = array_slice($refineModels, 0, 1);
$models = array_values(array_unique(array_merge($refineModels, [$gemmaModel])));
}
$promptVersion = 'pay_cv_fit_matrix_v9';
$batchSize = max(1, min(20, (int)(getenv('AI_FILTER_BATCH_SIZE') ?: 20)));
$gemmaFirstPassBatchLimit = strpos($gemmaModel, 'gemma-') === 0 ? 1 : 20;
$gemmaFirstPassBatchSize = max(1, min($gemmaFirstPassBatchLimit, (int)(getenv('AI_GEMMA_FIRST_PASS_BATCH_SIZE') ?: 1)));
$gemmaFirstPassRequestsPerRun = max(0, min(50, (int)(getenv('AI_GEMMA_FIRST_PASS_REQUESTS_PER_RUN') ?: 3)));
$flashLiteRefineBatchSize = max(1, min(20, (int)(getenv('AI_FLASH_LITE_REFINE_BATCH_SIZE') ?: 4)));
$priorityFirstPassModel = normalize_model_id(getenv('AI_PRIORITY_FIRST_PASS_MODEL') ?: $gemmaModel);
$prioritySecondPassModel = normalize_model_id(getenv('AI_PRIORITY_SECOND_PASS_MODEL') ?: $gemmaModel);
$priorityArbiterModel = normalize_model_id(getenv('AI_PRIORITY_ARBITER_MODEL') ?: ($refineModels[1] ?? ($refineModels[0] ?? 'gemini-3-flash')));
$priorityArbiterBatchSize = max(1, min(50, (int)(getenv('AI_PRIORITY_ARBITER_BATCH_SIZE') ?: 20)));
$contentChars = max(200, min(2400, (int)(getenv('AI_FILTER_CONTENT_CHARS') ?: 900)));
$jobTypeOptionLimit = max(1, min(50, (int)(getenv('AI_JOB_TYPE_OPTION_LIMIT') ?: 25)));
$intervalSeconds = max(10, min(86400, (int)(getenv('AI_FILTER_INTERVAL_SECONDS') ?: 20)));
$lookbackDays = max(1, min(90, (int)(getenv('AI_FILTER_LOOKBACK_DAYS') ?: 14)));
$quotaCooldownSeconds = max(300, min(86400, (int)(getenv('AI_FILTER_QUOTA_COOLDOWN_SECONDS') ?: 21600)));
$dailyRequestBudget = max(0, min(100000, (int)(getenv('AI_FILTER_DAILY_REQUEST_BUDGET') ?: 0)));
$modelDailyLimits = parse_model_daily_limits(getenv('AI_MODEL_DAILY_LIMITS') ?: 'gemini-3.1-flash-lite=500,gemini-3-flash=20,gemma4-31b=1500');
$entryIds = array_values(array_filter(array_map('trim', explode(',', getenv('AI_FILTER_ENTRY_IDS') ?: '')), static fn(string $id): bool => preg_match('/^\d+$/', $id) === 1));
$statePath = getenv('AI_FILTER_STATE_FILE') ?: "/var/www/FreshRSS/data/users/{$user}/rss_leads_ai_state.json";
$cvProfilePath = getenv('RSS_LEADS_CV_PROFILE_FILE') ?: "/var/www/FreshRSS/data/users/{$user}/rss_leads_profile.json";
$cvProfileData = is_readable($cvProfilePath) ? json_decode((string)file_get_contents($cvProfilePath), true) : [];
$cvProfile = is_array($cvProfileData) ? compact_text((string)($cvProfileData['profile'] ?? ''), 12000) : '';
$promptVersion .= '_' . substr(hash('sha256', $cvProfile), 0, 12);
$highPrioritySyncPath = '/opt/rss-leads-stack/scripts/sync-freshrss-high-priority.php';
if (is_file($highPrioritySyncPath)) {
require_once $highPrioritySyncPath;
}
if (!defined('RSS_LEADS_RECOVERED_FEED')) {
define('RSS_LEADS_RECOVERED_FEED', 'Recovered Reddit Leads - AI classified history');
}
function normalize_model_id(string $model): string {
return RssLeadsModelIds::normalize($model);
}
function parse_model_daily_limits(string $value): array {
return RssLeadsModelIds::dailyLimits($value);
}
function load_state(string $path): array {
return RssLeadsJsonFile::readArray($path);
}
function save_state(string $path, array $state): void {
$state['updated_at'] = time();
RssLeadsJsonFile::writeArrayAtomic($path, $state);
}
function push_limited(array &$state, string $key, array $item, int $limit): void {
RssLeadsAiState::pushLimited($state, $key, $item, $limit);
}
function bump_counter(array &$state, string $group, string $key, int $amount = 1): void {
RssLeadsAiState::bumpCounter($state, $group, $key, $amount);
}
function error_excerpt(string $value, int $limit = 700): string {
return RssLeadsText::errorExcerpt($value, $limit);
}
function record_error(array &$state, string $stage, string $type, string $message, array $context = []): void {
RssLeadsAiState::recordError($state, $stage, $type, $message, $context);
}
function record_request(array &$state, array $attempt, bool $ok, ?int $retryDelay = null): void {
RssLeadsAiState::recordRequest($state, $attempt, $ok, $retryDelay);
}
function budget_key(int $timestamp): string {
$dt = new DateTimeImmutable('@' . $timestamp);
return $dt->setTimezone(new DateTimeZone('Asia/Kolkata'))->format('Y-m-d');
}
function reset_daily_budget_if_needed(array &$state, int $now, int $dailyRequestBudget): void {
$key = budget_key($now);
$remaining = $dailyRequestBudget > 0 ? max(0, $dailyRequestBudget) : null;
if (!isset($state['daily_budget']) || !is_array($state['daily_budget']) || ($state['daily_budget']['date'] ?? '') !== $key) {
$recordedToday = 0;
foreach ($state['requests'] ?? [] as $request) {
if (is_array($request) && budget_key((int)($request['at'] ?? 0)) === $key) {
$recordedToday++;
}
}
$remaining = $dailyRequestBudget > 0 ? max(0, $dailyRequestBudget - $recordedToday) : null;
$state['daily_budget'] = [
'date' => $key,
'limit' => $dailyRequestBudget,
'used' => $recordedToday,
'remaining' => $remaining,
'reset_at' => (new DateTimeImmutable($key . ' 00:00:00', new DateTimeZone('Asia/Kolkata')))->modify('+1 day')->getTimestamp(),
];
}
$state['daily_budget']['limit'] = $dailyRequestBudget;
$recordedToday = 0;
foreach ($state['requests'] ?? [] as $request) {
if (is_array($request) && budget_key((int)($request['at'] ?? 0)) === $key) {
$recordedToday++;
}
}
$state['daily_budget']['used'] = max($recordedToday, (int)($state['daily_budget']['used'] ?? 0));
$state['daily_budget']['remaining'] = $dailyRequestBudget > 0 ? max(0, $dailyRequestBudget - $state['daily_budget']['used']) : null;
}
function consume_daily_request(array &$state, int $dailyRequestBudget): void {
reset_daily_budget_if_needed($state, time(), $dailyRequestBudget);
$state['daily_budget']['used']++;
$state['daily_budget']['remaining'] = $dailyRequestBudget > 0 ? max(0, $dailyRequestBudget - (int)$state['daily_budget']['used']) : null;
}
function reset_model_daily_limits_if_needed(array &$state, int $now, array $modelDailyLimits): void {
$key = budget_key($now);
if (!isset($state['model_daily_budgets']) || !is_array($state['model_daily_budgets']) || ($state['model_daily_budgets']['date'] ?? '') !== $key) {
$state['model_daily_budgets'] = [
'date' => $key,
'models' => [],
'reset_at' => (new DateTimeImmutable($key . ' 00:00:00', new DateTimeZone('Asia/Kolkata')))->modify('+1 day')->getTimestamp(),
];
}
$state['model_daily_budgets']['date'] = $key;
$state['model_daily_budgets']['reset_at'] = (new DateTimeImmutable($key . ' 00:00:00', new DateTimeZone('Asia/Kolkata')))->modify('+1 day')->getTimestamp();
if (!isset($state['model_daily_budgets']['models']) || !is_array($state['model_daily_budgets']['models'])) {
$state['model_daily_budgets']['models'] = [];
}
foreach ($modelDailyLimits as $model => $limit) {
$used = (int)($state['model_daily_budgets']['models'][$model]['used'] ?? 0);
$state['model_daily_budgets']['models'][$model] = [
'limit' => $limit,
'used' => $used,
'remaining' => max(0, $limit - $used),
];
}
foreach (array_keys($state['model_daily_budgets']['models']) as $model) {
if (!isset($modelDailyLimits[$model])) {
unset($state['model_daily_budgets']['models'][$model]);
}
}
}
function model_daily_budget_available(array &$state, string $model, array $modelDailyLimits): bool {
if (!isset($modelDailyLimits[$model])) {
return true;
}
reset_model_daily_limits_if_needed($state, time(), $modelDailyLimits);
return (int)($state['model_daily_budgets']['models'][$model]['remaining'] ?? 0) > 0;
}
function consume_model_daily_request(array &$state, string $model, array $modelDailyLimits): void {
if (!isset($modelDailyLimits[$model])) {
return;
}
reset_model_daily_limits_if_needed($state, time(), $modelDailyLimits);
$state['model_daily_budgets']['models'][$model]['used']++;
$limit = (int)$state['model_daily_budgets']['models'][$model]['limit'];
$state['model_daily_budgets']['models'][$model]['remaining'] = max(0, $limit - (int)$state['model_daily_budgets']['models'][$model]['used']);
}
function local_not_hiring_summary(array $group): ?string {
$title = mb_strtolower((string)($group['title'] ?? ''), 'UTF-8');
$text = mb_strtolower((string)($group['text'] ?? ''), 'UTF-8');
$combined = $title . ' ' . $text;
$notHiringRules = [
'Freelancer offer, not a buyer hiring for a role.' => [
'/\[(for hire|hire me|offer)\]/u',
'/\b(for hire|hire me|available for work|open to work|portfolio|my services|i offer|i can help|web developer for hire|video editor for hire)\b/u',
],
'Advice or discussion post, not a hiring lead.' => [
'/\b(advice|help me|question|how do i|what should i|discussion|feedback|review my|begging for help|problem with|struggling with)\b/u',
],
'Showcase or self-promotion, not a hiring lead.' => [
'/\b(showcase|case study|launched|built this|check out|self promotion|advertisement|promoting|newsletter|course|template)\b/u',
],
'Seller-side prospecting, not someone hiring.' => [
'/\b(looking for clients|lead generation|appointment setter|how to get clients|sell my service|find customers)\b/u',
],
'Job seeker post, not a hiring lead.' => [
'/\b(resume|cv|job seeker|seeking work|looking for work|internship wanted|entry level candidate)\b/u',
],
];
foreach ($notHiringRules as $summary => $patterns) {
foreach ($patterns as $pattern) {
if (preg_match($pattern, $combined) === 1) {
return $summary;
}
}
}
$hiringSignals = [
'/\b(hiring|paid|paying|budget|looking for|need(?:ed)?|seeking|wanted|task|job|role|position|contract|editor needed|developer needed|will pay)\b/u',
'/\[(hiring|paid|task)\]/u',
];
foreach ($hiringSignals as $pattern) {
if (preg_match($pattern, $combined) === 1) {
return null;
}
}
return null;
}
function start_run(array &$state, int $startedAt, int $intervalSeconds, array $config): void {
$state['current_status'] = 'running';
$state['last_started_at'] = $startedAt;
$state['next_run_at'] = $startedAt + $intervalSeconds;
$state['config'] = $config;
bump_counter($state, 'run_counts', 'total');
}
function finish_run(array &$state, string $status, int $finishedAt, string $message, array $batch = []): void {
$state['current_status'] = $status;
$state['last_finished_at'] = $finishedAt;
$state['last_message'] = $message;
if ($status === 'success') {
$state['last_success_at'] = $finishedAt;
bump_counter($state, 'run_counts', 'success');
} elseif ($status === 'skipped') {
$state['last_skipped_at'] = $finishedAt;
bump_counter($state, 'run_counts', 'skipped');
} else {
$state['last_failed_at'] = $finishedAt;
bump_counter($state, 'run_counts', 'failed');
}
if (!empty($batch)) {
$state['last_batch'] = $batch;
}
}
function active_model_backoffs(array $state, array $models, int $now): array {
$active = [];
foreach ($models as $model) {
$until = (int)($state['model_backoffs'][$model] ?? 0);
if ($until > $now) {
$active[$model] = $until;
}
}
return $active;
}
$state = load_state($statePath);
$runStarted = time();
start_run($state, $runStarted, $intervalSeconds, [
'batch_size' => $batchSize,
'content_chars' => $contentChars,
'job_type_option_limit' => $jobTypeOptionLimit,
'lookback_days' => $lookbackDays,
'interval_seconds' => $intervalSeconds,
'quota_cooldown_seconds' => $quotaCooldownSeconds,
'models' => $models,
'gemma_model' => $gemmaModel,
'refine_models' => $refineModels,
'priority_first_pass_model' => $priorityFirstPassModel,
'priority_second_pass_model' => $prioritySecondPassModel,
'priority_arbiter_model' => $priorityArbiterModel,
'priority_arbiter_batch_size' => $priorityArbiterBatchSize,
'gemma_first_pass_batch_size' => $gemmaFirstPassBatchSize,
'gemma_first_pass_requests_per_run' => $gemmaFirstPassRequestsPerRun,
'flash_lite_refine_batch_size' => $flashLiteRefineBatchSize,
'allow_model_fallbacks' => $allowModelFallbacks,
'daily_request_budget' => $dailyRequestBudget,
'model_daily_limits' => $modelDailyLimits,
'prompt_version' => $promptVersion,
]);
reset_daily_budget_if_needed($state, $runStarted, $dailyRequestBudget);
reset_model_daily_limits_if_needed($state, $runStarted, $modelDailyLimits);
save_state($statePath, $state);
if ($apiKey === '') {
$message = 'GEMINI_API_KEY is not set; skipping AI filter.';
record_error($state, 'config', 'missing_api_key', $message);
finish_run($state, 'skipped', time(), $message);
save_state($statePath, $state);
fwrite(STDERR, $message . "\n");
exit(0);
}
$activeModelBackoffs = active_model_backoffs($state, $models, time());
if (!empty($models) && count($activeModelBackoffs) === count($models)) {
$nextModelBackoff = min($activeModelBackoffs);
$message = 'All Gemini fallback models are in quota backoff until ' . date(DATE_ATOM, $nextModelBackoff) . '; skipping AI filter.';
$state['quota_backoff_until'] = $nextModelBackoff;
$state['next_batch_at'] = max((int)($state['next_run_at'] ?? 0), $nextModelBackoff);
finish_run($state, 'skipped', time(), $message, [
'candidate_rows' => 0,
'unique_links' => 0,
'local_classified' => 0,
'sent_items' => 0,
'returned_items' => 0,
'saved' => 0,
'skipped_reason' => 'all_models_quota_backoff',
'model_backoffs' => $activeModelBackoffs,
'daily_budget' => $state['daily_budget'] ?? null,
]);
save_state($statePath, $state);
fwrite(STDERR, $message . "\n");
exit(0);
}
function compact_text(string $html, int $limit): string {
$text = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8');
$text = preg_replace('/\s+/u', ' ', $text) ?? $text;
$text = trim($text);
if (mb_strlen($text, 'UTF-8') > $limit) {
$text = mb_substr($text, 0, $limit, 'UTF-8');
}
return $text;
}
function subreddit_from_url(string $url): string {
if (preg_match('~reddit\.com/r/([A-Za-z0-9_]{2,21})~i', $url, $match)) {
return $match[1];
}
return '';
}
function normalize_priority(string $priority): string {
$priority = mb_strtolower(trim($priority), 'UTF-8');
$priority = preg_replace('/[\s-]+/u', '_', $priority) ?? $priority;
if (in_array($priority, ['xhigh', 'extra_high', 'very_high'], true)) {
return 'x_high';
}
if (in_array($priority, ['not_hire', 'not_hiring_lead'], true)) {
return 'not_hiring';
}
return $priority;
}
function valid_priorities(): array {
return ['low', 'medium', 'high', 'x_high', 'not_hiring'];
}
function normalize_cv_fit(mixed $value): string {
return RssLeadsPriority::normalizeCvFit($value);
}
function priority_has_budget(string $priority): bool {
return in_array($priority, ['medium', 'high', 'x_high'], true);
}
function priority_rank(string $priority): int {
return match ($priority) {
'x_high' => 4,
'high' => 3,
'medium' => 2,
'low' => 1,
'not_hiring' => -1,
default => 0,
};
}
function normalize_monthly_amount(string $value, string $priority): string {
if (!priority_has_budget($priority)) {
return '';
}
$value = html_entity_decode(strip_tags($value), ENT_QUOTES | ENT_HTML5, 'UTF-8');
$value = preg_replace('/\s+/u', ' ', $value) ?? $value;
$value = trim($value);
if ($value === '' || preg_match('/^(unknown|unclear|not specified|n\/a|na|none)$/iu', $value) === 1) {
return 'unknown';
}
if (mb_strlen($value, 'UTF-8') > 64) {
$value = mb_substr($value, 0, 64, 'UTF-8');
}
return $value;
}
function parse_money_value(string $amount, string $suffix = ''): float {
$value = (float)str_replace(',', '', $amount);
if (in_array(strtolower($suffix), ['k', 'm'], true)) {
$value *= strtolower($suffix) === 'm' ? 1000000 : 1000;
}
return $value;
}
function format_monthly_amount(float $min, ?float $max = null, string $suffix = '/mo'): string {
$max ??= $min;
$min = max(1, round($min));
$max = max(1, round($max));
if ($max < $min) {
[$min, $max] = [$max, $min];
}
$format = static fn(float $value): string => '$' . number_format((int)$value);
if (abs($max - $min) <= 1) {
return $format($min) . $suffix;
}
return $format($min) . '-' . $format($max) . $suffix;
}
function estimate_monthly_amount_from_text(string $title, string $content): string {
$text = compact_text($title . ' ' . $content, 2400);
$money = '[$]\s*([0-9][0-9,]*(?:\.[0-9]+)?)\s*([kKmM]?)';
$range = $money . '(?:\s*(?:-|\x{2013}|to)\s*[$]?\s*([0-9][0-9,]*(?:\.[0-9]+)?)\s*([kKmM]?))?';
$patterns = [
['~' . $range . '\s*(?:/mo|/month|per month|monthly)\b~iu', 1.0, '/mo'],
['~' . $range . '\s*(?:/wk|/week|per week|weekly)\b~iu', 4.33, '/mo'],
['~' . $range . '\s*(?:/hr|/hour|per hour|hourly)\b~iu', 160.0, '/mo'],
['~' . $range . '\s*(?:/yr|/year|per year|yearly|annual|annually|salary)\b~iu', 1 / 12, '/mo'],
];
foreach ($patterns as [$pattern, $multiplier, $suffix]) {
if (preg_match($pattern, $text, $match) === 1) {
$min = parse_money_value($match[1], $match[2] ?? '') * $multiplier;
$max = isset($match[3]) && $match[3] !== '' ? parse_money_value($match[3], $match[4] ?? '') * $multiplier : $min;
return format_monthly_amount($min, $max, $suffix);
}
}
if (preg_match('~(?:budget|pay|paid|payment|salary|rate)[^$]{0,24}' . $range . '~iu', $text, $match) === 1) {
$min = parse_money_value($match[1], $match[2] ?? '');
$max = isset($match[3]) && $match[3] !== '' ? parse_money_value($match[3], $match[4] ?? '') : $min;
return format_monthly_amount($min, $max, '/mo equiv');
}
return 'unknown';
}
function money_floor_priority_from_text(string $title, string $content): ?string {
$text = compact_text($title . ' ' . $content, 2400);
$money = '[$]\s*([0-9][0-9,]*(?:\.[0-9]+)?)\s*([kKmM]?)';
$range = $money . '(?:\s*(?:-|\x{2013}|to)\s*[$]?\s*([0-9][0-9,]*(?:\.[0-9]+)?)\s*([kKmM]?))?';
$patterns = [
['~' . $range . '\s*(?:/hr|/hour|per hour|hourly)\b~iu', static fn(float $max): bool => $max > 5],
['~' . $range . '\s*(?:/mo|/month|per month|monthly)\b~iu', static fn(float $max): bool => $max >= 200],
['~' . $range . '\s*(?:/wk|/week|per week|weekly)\b~iu', static fn(float $max): bool => ($max * 4.33) >= 200],
['~' . $range . '\s*(?:/yr|/year|per year|yearly|annual|annually|salary)\b~iu', static fn(float $max): bool => ($max / 12) >= 200],
['~(?:budget|pay|paid|payment|rate)[^$]{0,24}' . $range . '~iu', static fn(float $max): bool => $max >= 200],
];
foreach ($patterns as [$pattern, $isMediumOrBetter]) {
if (preg_match($pattern, $text, $match) !== 1) {
continue;
}
$min = parse_money_value($match[1], $match[2] ?? '');
$max = isset($match[3]) && $match[3] !== '' ? parse_money_value($match[3], $match[4] ?? '') : $min;
if ($max < $min) {
[$min, $max] = [$max, $min];
}
if ($isMediumOrBetter($max)) {
return 'medium';
}
}
return null;
}
function apply_money_priority_floor(string $priority, array $group): string {
if ($priority === 'not_hiring' || priority_rank($priority) >= priority_rank('medium')) {
return $priority;
}
$floor = money_floor_priority_from_text((string)($group['title'] ?? ''), (string)($group['text'] ?? ''));
if ($floor !== null && priority_rank($floor) > priority_rank($priority)) {
return $floor;
}
return $priority;
}
function monthly_amount_for_result(array $result, array $group, string $priority): string {
$monthlyAmount = normalize_monthly_amount((string)($result['monthly_amount'] ?? ''), $priority);
if (priority_has_budget($priority) && $monthlyAmount === 'unknown') {
$monthlyAmount = estimate_monthly_amount_from_text((string)($group['title'] ?? ''), (string)($group['text'] ?? ''));
}
return $monthlyAmount;
}
function payment_is_known(string $monthlyAmount): bool {
$monthlyAmount = trim(mb_strtolower($monthlyAmount, 'UTF-8'));
return $monthlyAmount !== '' && $monthlyAmount !== 'unknown';
}
function enforce_high_requires_known_payment(string $priority, string $monthlyAmount): string {
if (in_array($priority, ['high', 'x_high'], true) && !payment_is_known($monthlyAmount)) {
return 'medium';
}
return $priority;
}
function monthly_amount_max(string $value): ?float {
return RssLeadsPriority::monthlyAmountMax($value);
}
function priority_from_pay_and_fit(string $current, string $monthlyAmount, string $cvFit, bool $portfolioAvailable): string {
return RssLeadsPriority::fromPayAndFit($current, $monthlyAmount, $cvFit, $portfolioAvailable);
}
function finalize_priority_and_amount(array $result, array $group): array {
$priority = normalize_priority((string)($result['priority'] ?? 'low'));
if (!in_array($priority, valid_priorities(), true)) {
$priority = 'low';
}
$cvFit = !empty($group['cv_profile_available']) ? normalize_cv_fit($result['cv_fit'] ?? 'low') : 'low';
$monthlyAmount = normalize_monthly_amount((string)($result['monthly_amount'] ?? ''), 'medium');
if ($monthlyAmount === 'unknown') {
$monthlyAmount = estimate_monthly_amount_from_text((string)($group['title'] ?? ''), (string)($group['text'] ?? ''));
}
$priority = priority_from_pay_and_fit($priority, $monthlyAmount, $cvFit, !empty($group['cv_profile_available']));
if (!priority_has_budget($priority)) {
$monthlyAmount = '';
} elseif ($priority === 'medium' && $monthlyAmount === '') {
$monthlyAmount = 'unknown';
}
return [$priority, $monthlyAmount, $cvFit];
}
function normalize_existing_priority_matrix(PDO $db, bool $portfolioAvailable): array {
$rows = $db->query(
'SELECT ai.entry_id, ai.priority, ai.monthly_amount, ai.job_type, ai.cv_fit, ai.scam_likelihood,
e.title, e.content, e.tags
FROM rss_leads_ai ai
LEFT JOIN entry e ON e.id = ai.entry_id'
)->fetchAll(PDO::FETCH_ASSOC);
$updateAi = $db->prepare('UPDATE rss_leads_ai SET priority = :priority, monthly_amount = :monthly_amount, cv_fit = :cv_fit WHERE entry_id = :entry_id');
$updateEntry = $db->prepare('UPDATE entry SET tags = :tags, lastUserModified = :updated_at WHERE id = :entry_id');
$changed = 0;
$db->beginTransaction();
try {
foreach ($rows as $row) {
$current = normalize_priority((string)$row['priority']);
$cvFit = normalize_cv_fit($row['cv_fit'] ?? 'low');
$monthlyAmount = normalize_monthly_amount((string)($row['monthly_amount'] ?? ''), 'medium');
if ($monthlyAmount === 'unknown') {
$monthlyAmount = estimate_monthly_amount_from_text((string)($row['title'] ?? ''), (string)($row['content'] ?? ''));
}
$priority = priority_from_pay_and_fit($current, $monthlyAmount, $cvFit, $portfolioAvailable);
$storedAmount = priority_has_budget($priority) ? $monthlyAmount : '';
if ($priority === $current && $storedAmount === (string)$row['monthly_amount'] && $cvFit === (string)$row['cv_fit']) {
continue;
}
$updateAi->execute([
':priority' => $priority,
':monthly_amount' => $storedAmount,
':cv_fit' => $cvFit,
':entry_id' => (int)$row['entry_id'],
]);
if ($row['tags'] !== null) {
$updateEntry->execute([
':tags' => tags_with_ai_labels((string)$row['tags'], $priority, $storedAmount, (string)$row['job_type'], (int)$row['scam_likelihood']),
':updated_at' => time(),
':entry_id' => (int)$row['entry_id'],
]);
}
$changed++;
}
$db->commit();
} catch (Throwable $e) {
if ($db->inTransaction()) {
$db->rollBack();
}
throw $e;
}
return ['checked' => count($rows), 'changed' => $changed];
}
function normalize_job_type(string $value, string $priority): string {
if ($priority === 'not_hiring') {
return '';
}
$value = html_entity_decode(strip_tags($value), ENT_QUOTES | ENT_HTML5, 'UTF-8');
$value = mb_strtolower($value, 'UTF-8');
$value = str_replace('&', ' and ', $value);
$value = preg_replace('/^(?:job|role|type|category)\s*:\s*/u', '', $value) ?? $value;
$value = preg_replace('/[^a-z0-9+#\/ -]+/u', ' ', $value) ?? $value;
$value = preg_replace('/\s+/u', ' ', $value) ?? $value;
$value = trim($value, " \t\n\r\0\x0B-_/.");
if ($value === '' || preg_match('/^(?:unknown|unclear|not specified|n\/a|na|none|other)$/u', $value) === 1) {
return '';
}
$aliases = [
'video editor' => 'video editing',
'video production' => 'video editing',
'youtube editing' => 'video editing',
'script writing' => 'scriptwriting',
'script writer' => 'scriptwriting',
'youtube scriptwriting' => 'scriptwriting',
'copy writing' => 'content writing',
'copywriting' => 'content writing',
'social media manager' => 'social media management',
'community management' => 'social media management',
'workflow automation' => 'automation',
'n8n automation' => 'automation',
'web developer' => 'web development',
'website development' => 'web development',
'graphic designer' => 'graphic design',
'thumbnail designer' => 'thumbnail design',
'podcast editor' => 'podcast editing',
'voice over' => 'voiceover',
'voice actor' => 'voiceover',
'virtual assistance' => 'virtual assistant',
'mobile app developer' => 'mobile app development',
'chatbot development' => 'ai chatbot',
];
if (isset($aliases[$value])) {
return $aliases[$value];
}
$words = preg_split('/\s+/', $value) ?: [];
if (count($words) > 5) {
$value = implode(' ', array_slice($words, 0, 5));
}
if (mb_strlen($value, 'UTF-8') > 64) {
$value = mb_substr($value, 0, 64, 'UTF-8');
$value = trim($value);
}
return $value;
}
function estimate_job_type_from_text(string $title, string $content): string {
$text = mb_strtolower(compact_text($title . ' ' . $content, 2400), 'UTF-8');
$rules = [
'video editing' => '/\b(video edit(?:or|ing)?|youtube editor|shorts editor|reels editor|tiktok editor|premiere pro|after effects)\b/u',
'scriptwriting' => '/\b(script ?writer|script writing|write scripts?|youtube scripts?|screenwriter)\b/u',
'content writing' => '/\b(content writer|copywriter|blog writer|article writer|ghostwriter|writing job)\b/u',
'social media management' => '/\b(social media manager|community manager|instagram|twitter|x account|tiktok account|content calendar)\b/u',
'automation' => '/\b(automation|n8n|zapier|make\.com|workflow|integrations?)\b/u',
'web development' => '/\b(web developer|website|wordpress|shopify|frontend|backend|landing page)\b/u',
'graphic design' => '/\b(graphic designer|logo|brand design|banner|creative design)\b/u',
'thumbnail design' => '/\b(thumbnail|youtube thumb)\b/u',
'podcast editing' => '/\b(podcast editor|audio editor|podcast editing)\b/u',
'voiceover' => '/\b(voice ?over|voice actor|narration)\b/u',
'seo' => '/\b(seo|search engine optimization|backlinks?)\b/u',
'virtual assistant' => '/\b(virtual assistant|admin assistant|executive assistant|va\b)\b/u',
'mobile app development' => '/\b(mobile app|ios app|android app|react native|flutter)\b/u',
'ai chatbot' => '/\b(chatbot|ai agent|llm|openai|gemini bot)\b/u',
'data entry' => '/\b(data entry|spreadsheet|excel|google sheets)\b/u',
'lead generation' => '/\b(lead generation|appointment setting|cold email|outreach)\b/u',
];
foreach ($rules as $jobType => $pattern) {
if (preg_match($pattern, $text) === 1) {
return $jobType;
}
}
return 'general help';
}
function job_type_for_result(array $result, array $group, string $priority): string {
$jobType = normalize_job_type((string)($result['job_type'] ?? ''), $priority);
if ($priority !== 'not_hiring' && $jobType === '') {
$jobType = estimate_job_type_from_text((string)($group['title'] ?? ''), (string)($group['text'] ?? ''));
}
return $jobType;
}
function scam_likelihood_for_result(array $result): int {
if (!array_key_exists('scam_likelihood', $result) || !is_numeric($result['scam_likelihood'])) {
return 0;
}
return max(0, min(100, (int)round((float)$result['scam_likelihood'])));
}
function ai_tag_value(string $value, string $fallback = 'unknown'): string {
$value = html_entity_decode(strip_tags($value), ENT_QUOTES | ENT_HTML5, 'UTF-8');
$value = mb_strtolower($value, 'UTF-8');
$value = str_replace('&', 'and', $value);
$value = preg_replace('/\s+/u', '_', $value) ?? $value;
$value = preg_replace('/[^a-z0-9$.,:+\/_-]+/u', '', $value) ?? $value;
$value = trim($value, '_');
return $value === '' ? $fallback : $value;
}
function scam_likelihood_tag(int $score): string {
if ($score >= 70) {
return 'scam:high';
}
if ($score >= 35) {
return 'scam:medium';
}
return 'scam:low';
}
function tags_with_ai_labels(string $tags, string $priority, string $monthlyAmount, string $jobType, int $scamLikelihood): string {
$existing = preg_split('/\s+/', trim($tags)) ?: [];
$merged = [];
foreach ($existing as $tag) {
$tag = trim($tag);
$lowerTag = mb_strtolower($tag, 'UTF-8');
if (
$tag === ''
|| str_starts_with($lowerTag, 'priority:')
|| str_starts_with($lowerTag, 'monthly:')
|| str_starts_with($lowerTag, 'job:')
|| str_starts_with($lowerTag, 'scam:')
) {
continue;
}
$merged[$tag] = true;
}
$merged['priority:' . ai_tag_value($priority)] = true;
if ($monthlyAmount !== '') {
$merged['monthly:' . ai_tag_value($monthlyAmount)] = true;
}
if ($jobType !== '') {
$merged['job:' . ai_tag_value($jobType)] = true;
}
if ($scamLikelihood > 0) {
$merged[scam_likelihood_tag($scamLikelihood)] = true;
}
return implode(' ', array_keys($merged));
}
function job_type_slug(string $jobType): string {
$slug = mb_strtolower($jobType, 'UTF-8');
$slug = str_replace('&', ' and ', $slug);
$slug = preg_replace('/[^a-z0-9+#\/]+/u', '-', $slug) ?? $slug;
$slug = preg_replace('/-+/u', '-', $slug) ?? $slug;
return trim($slug, '-');
}
function run_classification_batch(
string $apiKey,
array $models,
array $items,
array &$state,
string $statePath,
int $dailyRequestBudget,
array $modelDailyLimits,
array $jobTypeOptions,
int $quotaCooldownSeconds,
int $intervalSeconds,
string $payloadMode = 'classify'
): array {
foreach ($models as $candidateModel) {
$expectedIds = array_values(array_map(static fn(array $item): string => (string)($item['id'] ?? ''), $items));
$modelBackoffUntil = (int)($state['model_backoffs'][$candidateModel] ?? 0);
if ($modelBackoffUntil > time()) {
record_error($state, 'budget', 'model_quota_backoff_active', 'Skipping model due to active quota backoff.', [
'model' => $candidateModel,
'backoff_until' => $modelBackoffUntil,
]);
continue;
}
reset_daily_budget_if_needed($state, time(), $dailyRequestBudget);
if ($dailyRequestBudget > 0 && (int)($state['daily_budget']['remaining'] ?? 0) <= 0) {
$message = 'Daily Gemini request budget used before model request.';
record_error($state, 'budget', 'daily_request_budget_exhausted', $message, [
'model' => $candidateModel,
'daily_budget' => $state['daily_budget'],
]);
break;
}
reset_model_daily_limits_if_needed($state, time(), $modelDailyLimits);
if (!model_daily_budget_available($state, $candidateModel, $modelDailyLimits)) {
$resetAt = (int)($state['model_daily_budgets']['reset_at'] ?? (time() + 86400));
if (!isset($state['model_backoffs']) || !is_array($state['model_backoffs'])) {
$state['model_backoffs'] = [];
}
$state['model_backoffs'][$candidateModel] = $resetAt;
record_error($state, 'budget', 'model_daily_limit_exhausted', 'Local model daily request limit reached.', [
'model' => $candidateModel,
'backoff_until' => $resetAt,
'model_daily_budget' => $state['model_daily_budgets']['models'][$candidateModel] ?? null,
]);
continue;
}
consume_daily_request($state, $dailyRequestBudget);
consume_model_daily_request($state, $candidateModel, $modelDailyLimits);
save_state($statePath, $state);
$gemini = new GeminiClient($apiKey, $quotaCooldownSeconds, $intervalSeconds);
$payload = $payloadMode === 'arbitrate'
? GeminiClient::buildArbitrationPayload($items, $candidateModel, $jobTypeOptions)
: GeminiClient::buildPayload($items, $candidateModel, $jobTypeOptions);
$attempt = $gemini->call($candidateModel, $payload);
if ($attempt['raw'] !== '' && $attempt['status'] >= 200 && $attempt['status'] < 300) {
record_request($state, $attempt, true);
$response = json_decode($attempt['raw'], true);
$text = is_array($response) ? GeminiClient::extractText($response) : '';
$decoded = GeminiClient::decodeJsonArray($text, $expectedIds);
if (is_array($decoded)) {
if (isset($state['model_backoffs'][$candidateModel])) {
unset($state['model_backoffs'][$candidateModel]);
}
$state['quota_backoff_until'] = 0;
return ['results' => $decoded, 'model' => $candidateModel];
}
$message = "Gemini returned non-JSON model={$candidateModel} result=" . mb_substr($text, 0, 500, 'UTF-8');
record_error($state, 'gemini_response', 'invalid_json', $message, [
'model' => $candidateModel,
'status' => $attempt['status'],
]);
fwrite(STDERR, $message . "\n");
continue;
}
fwrite(STDERR, "Gemini request failed model={$candidateModel} status={$attempt['status']} error={$attempt['error']} body={$attempt['raw']}\n");
$retryDelay = $attempt['status'] === 429 ? (GeminiClient::parseRetryDelay($attempt['raw']) ?? 0) : null;
record_request($state, $attempt, false, $retryDelay);
record_error($state, 'gemini_request', $attempt['status'] === 429 ? 'quota_exhausted' : 'request_failed', (string)($attempt['raw'] ?: $attempt['error'] ?: 'Gemini request failed.'), [
'model' => $candidateModel,
'status' => $attempt['status'],
'retry_delay_seconds' => $retryDelay,
]);
if ($attempt['status'] === 429) {
$modelBackoffUntil = time() + max($quotaCooldownSeconds, $retryDelay);
if (!isset($state['model_backoffs']) || !is_array($state['model_backoffs'])) {
$state['model_backoffs'] = [];
}
$state['model_backoffs'][$candidateModel] = $modelBackoffUntil;
$state['last_quota_error_at'] = time();
$state['last_quota_model'] = $candidateModel;
$state['next_batch_at'] = (int)($state['next_run_at'] ?? (time() + $intervalSeconds));
save_state($statePath, $state);
fwrite(STDERR, 'Gemini quota exhausted for model=' . $candidateModel . '; backing that model off until ' . date(DATE_ATOM, $modelBackoffUntil) . ".\n");
continue;
}
}
return ['results' => null, 'model' => null];
}
function results_by_id(array $results): array {
$mapped = [];
foreach ($results as $result) {
if (!is_array($result)) {
continue;
}
$id = (string)($result['id'] ?? '');
if ($id !== '') {
$mapped[$id] = $result;
}
}
return $mapped;
}
function result_priority(array $result): string {
$priority = normalize_priority((string)($result['priority'] ?? 'low'));
return in_array($priority, valid_priorities(), true) ? $priority : 'low';
}
function build_arbiter_items(array $itemsById, array $firstById, array $secondById): array {
$arbiterItems = [];
foreach ($itemsById as $id => $item) {
if (!isset($firstById[$id], $secondById[$id])) {
continue;
}
if (result_priority($firstById[$id]) === result_priority($secondById[$id])) {
continue;
}
$arbiterItem = $item;
$arbiterItem['check_1'] = [
'summary' => (string)($firstById[$id]['summary'] ?? ''),
'priority' => result_priority($firstById[$id]),
'monthly_amount' => (string)($firstById[$id]['monthly_amount'] ?? ''),
'job_type' => (string)($firstById[$id]['job_type'] ?? ''),
'scam_likelihood' => scam_likelihood_for_result($firstById[$id]),
];
$arbiterItem['check_2'] = [
'summary' => (string)($secondById[$id]['summary'] ?? ''),
'priority' => result_priority($secondById[$id]),
'monthly_amount' => (string)($secondById[$id]['monthly_amount'] ?? ''),
'job_type' => (string)($secondById[$id]['job_type'] ?? ''),
'scam_likelihood' => scam_likelihood_for_result($secondById[$id]),
];
$arbiterItems[] = $arbiterItem;
}
return $arbiterItems;
}
function double_check_classification_batch(
string $apiKey,
string $firstModel,
string $secondModel,
string $arbiterModel,
array $items,
array &$state,
string $statePath,
int $dailyRequestBudget,
array $modelDailyLimits,
array $jobTypeOptions,
int $quotaCooldownSeconds,
int $intervalSeconds
): array {
$firstRun = run_classification_batch($apiKey, [$firstModel], $items, $state, $statePath, $dailyRequestBudget, $modelDailyLimits, $jobTypeOptions, $quotaCooldownSeconds, $intervalSeconds);
$secondRun = run_classification_batch($apiKey, [$secondModel], $items, $state, $statePath, $dailyRequestBudget, $modelDailyLimits, $jobTypeOptions, $quotaCooldownSeconds, $intervalSeconds);
$firstById = results_by_id(is_array($firstRun['results'] ?? null) ? $firstRun['results'] : []);
$secondById = results_by_id(is_array($secondRun['results'] ?? null) ? $secondRun['results'] : []);
$itemsById = [];
foreach ($items as $item) {
$id = (string)($item['id'] ?? '');
if ($id !== '') {
$itemsById[$id] = $item;
}
}
$arbiterById = [];
$arbiterItems = build_arbiter_items($itemsById, $firstById, $secondById);
$arbiterRun = ['results' => [], 'model' => null];
if (!empty($arbiterItems)) {
$arbiterRun = run_classification_batch($apiKey, [$arbiterModel], $arbiterItems, $state, $statePath, $dailyRequestBudget, $modelDailyLimits, $jobTypeOptions, $quotaCooldownSeconds, $intervalSeconds, 'arbitrate');
$arbiterById = results_by_id(is_array($arbiterRun['results'] ?? null) ? $arbiterRun['results'] : []);
}
$final = [];
$conflicts = 0;
foreach (array_keys($itemsById) as $id) {
if (isset($firstById[$id], $secondById[$id]) && result_priority($firstById[$id]) !== result_priority($secondById[$id])) {
$conflicts++;
if (isset($arbiterById[$id])) {
$final[] = $arbiterById[$id] + ['_decision_model' => (string)($arbiterRun['model'] ?? $arbiterModel), '_decision_source' => 'arbiter'];
continue;
}
}
if (isset($secondById[$id])) {
$final[] = $secondById[$id] + ['_decision_model' => (string)($secondRun['model'] ?? $secondModel), '_decision_source' => 'second_pass'];
} elseif (isset($firstById[$id])) {
$final[] = $firstById[$id] + ['_decision_model' => (string)($firstRun['model'] ?? $firstModel), '_decision_source' => 'first_pass'];
}
}
return [
'results' => $final,
'first_model' => (string)($firstRun['model'] ?? $firstModel),
'second_model' => (string)($secondRun['model'] ?? $secondModel),
'arbiter_model' => (string)($arbiterRun['model'] ?? ''),
'conflicts' => $conflicts,
'arbitrated' => count($arbiterById),
];
}
function ai_table_columns(PDO $db): array {
$columns = [];
foreach ($db->query('PRAGMA table_info(rss_leads_ai)')->fetchAll(PDO::FETCH_ASSOC) as $column) {
$name = (string)($column['name'] ?? '');
if ($name !== '') {
$columns[$name] = true;
}
}
return $columns;
}
function ensure_job_type_table(PDO $db): void {
$db->exec('CREATE TABLE IF NOT EXISTS rss_leads_job_types (
slug TEXT PRIMARY KEY,
name TEXT NOT NULL,
usage_count INTEGER NOT NULL DEFAULT 0,
first_seen_at INTEGER NOT NULL,
last_seen_at INTEGER NOT NULL
)');
$db->exec('CREATE INDEX IF NOT EXISTS idx_rss_leads_job_types_usage ON rss_leads_job_types(usage_count DESC, last_seen_at DESC)');
$db->exec('INSERT OR IGNORE INTO rss_leads_job_types (slug, name, usage_count, first_seen_at, last_seen_at)
SELECT DISTINCT
lower(replace(trim(job_type), \' \', \'-\')) AS slug,
trim(job_type) AS name,
0 AS usage_count,
COALESCE(MIN(updated_at), strftime(\'%s\', \'now\')) AS first_seen_at,
COALESCE(MAX(updated_at), strftime(\'%s\', \'now\')) AS last_seen_at
FROM rss_leads_ai
WHERE trim(job_type) != \'\'
GROUP BY trim(job_type)');
}
function load_job_type_options(PDO $db, int $limit): array {
$stmt = $db->prepare('SELECT name FROM rss_leads_job_types ORDER BY usage_count DESC, last_seen_at DESC, name ASC LIMIT :limit');
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
$options = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$name = normalize_job_type((string)($row['name'] ?? ''), 'medium');
if ($name !== '') {
$options[$name] = true;
}
}
return array_keys($options);
}
function record_job_type(PDOStatement $upsertJobType, string $jobType, int $now): void {
if ($jobType === '') {
return;
}
$slug = job_type_slug($jobType);
if ($slug === '') {
return;
}
$upsertJobType->execute([
':slug' => $slug,
':name' => $jobType,
':now' => $now,
]);
}
function migrate_ai_table(PDO $db): void {
$createSql = 'CREATE TABLE IF NOT EXISTS rss_leads_ai (
entry_id INTEGER PRIMARY KEY,
link TEXT NOT NULL,
summary TEXT NOT NULL,
priority TEXT NOT NULL CHECK(priority IN ("low", "medium", "high", "x_high", "not_hiring")),
monthly_amount TEXT NOT NULL DEFAULT \'\',
job_type TEXT NOT NULL DEFAULT \'\',