-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_context.txt
More file actions
2952 lines (2420 loc) · 124 KB
/
code_context.txt
File metadata and controls
2952 lines (2420 loc) · 124 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
# AI KNOWLEDGE BASE CODE CONTEXT
# Generated context from /home/adi235/MistralOCR
# Total files processed: 42
================================================================================
# COMMAND LINE INTERFACE
================================================================================
parser.add_argument('--pdf-dir', help='Directory containing PDF files', type=str, default='/home/adi235/MistralOCR/Instagram-Scraper/data/papers/pdf')
parser.add_argument('--text-dir', help='Directory containing text files', type=str, default='/home/adi235/MistralOCR/Instagram-Scraper/data/papers/text')
parser.add_argument('--pending-file', help='Path to the pending_papers.json file', type=str, default='/home/adi235/MistralOCR/Instagram-Scraper/data/papers/pending_papers.json')
parser.add_argument('--dry-run', action='store_true', help='Show what would be done without making changes')
parser.add_argument('--max-papers', help='Maximum number of papers to add to pending list', type=int, default=None)
parser.add_argument('--clear-pending', action='store_true', help='Clear the pending list before adding new papers')
parser.add_argument('--collect', action='store_true', help='Collect papers from ArXiv')
parser.add_argument('--download-only', action='store_true', help='Only download papers without processing')
parser.add_argument('--batch-process', action='store_true', help='Process previously downloaded PDFs')
parser.add_argument('--max', help='Maximum number of papers to process', type=int, default=50)
parser.add_argument('--url', help='Download and process a single paper from URL', type=str)
parser.add_argument('--urls-file', help='Path to a text file containing paper URLs (one per line)', type=str)
parser.add_argument('--download-url', help='Download a single paper from URL without processing', type=str)
parser.add_argument('--download-urls-file', help='Path to a text file containing paper URLs to download without processing', type=str)
parser.add_argument('--search-query', help='Custom search query for ArXiv (overrides config)', type=str)
parser.add_argument('--source-type', help='Filter by source type')
parser.add_argument('--top-k', help='Top K results to consider', type=int, default=10)
parser.add_argument('--max-tokens', help='Maximum tokens for context', type=int, default=MAX_TOKENS_DEFAULT)
parser.add_argument('--vector-weight', help='Weight for vector search (0-1)', type=float)
parser.add_argument('--keyword-weight', help='Weight for keyword search (0-1)', type=float)
parser.add_argument('--output', help='Output file for the generated prompt')
parser.add_argument('--account', help='Specific account to process', type=str)
parser.add_argument('--all', action='store_true', help='Process all accounts')
parser.add_argument('--force', action='store_true', help='Force reconversion of already converted files')
parser.add_argument('--list-accounts', action='store_true', help='List all available accounts')
parser.add_argument('--verbose', action='store_true', help='Print additional debug information')
parser.add_argument('--no-copy-videos', action='store_true', help='Skip copying video files to standard location')
parser.add_argument('--batch-size', help='Batch size for processing', type=int, default=10)
parser.add_argument('--max-items', help='Maximum number of items to process', type=int)
parser.add_argument('--source-type', help='Process only this source type (instagram, github, research_paper)')
parser.add_argument('--model', help='Name of the sentence-transformers model to use', default="multi-qa-mpnet-base-dot-v1")
parser.add_argument('--content-id', help='Process a specific content ID', type=int)
parser.add_argument('--force-update', action='store_true', help='Force update of existing embeddings')
parser.add_argument('--top-k', help='Number of results to show', type=int, default=5)
parser.add_argument('--source-type', help='Filter by source type')
parser.add_argument('--vector-weight', help='Weight for vector search (0-1)', type=float)
parser.add_argument('--keyword-weight', help='Weight for keyword search (0-1)', type=float)
parser.add_argument('--adaptive', action='store_true', help='Use adaptive weights based on query')
parser.add_argument('--concepts', action='store_true', help='List top concepts')
parser.add_argument('--categories', action='store_true', help='List concept categories')
parser.add_argument('--category', help='Show concepts in category', type=str)
parser.add_argument('--relationships', action='store_true', help='List relationship types')
parser.add_argument('--relationship-type', help='Show relationships of this type', type=str)
parser.add_argument('--search', help='Search concepts by name/description', type=str)
parser.add_argument('--concept-id', help='Show concept details by ID', type=int)
parser.add_argument('--concept-name', help='Show concept details by name', type=str)
parser.add_argument('--related', help='Show concepts related to a concept ID', type=int)
parser.add_argument('--content', help='Show content with a concept ID', type=int)
parser.add_argument('--limit', help='Limit results', type=int, default=20)
parser.add_argument('--content-id', help='Extract concepts from specific content item', type=int)
parser.add_argument('--batch', action='store_true', help='Process in batch mode')
parser.add_argument('--batch-size', help='Batch size for processing', type=int, default=10)
parser.add_argument('--max-items', help='Maximum number of items to process', type=int)
parser.add_argument('--force', action='store_true', help='Process items even if they already have concepts')
parser.add_argument('--output-dir', help='Output directory for visualizations', type=str, default="visualizations")
parser.add_argument('--concept-id', help='Visualize neighborhood of this concept', type=int)
parser.add_argument('--search', help='Search and visualize concepts', type=str)
parser.add_argument('--all', action='store_true', help='Generate all standard visualizations')
parser.add_argument('--min-confidence', help='Minimum confidence for relationships', type=float, default=0.5)
parser.add_argument('--min-references', help='Minimum reference count for concepts', type=int, default=1)
parser.add_argument('--interactive', action='store_true', help='Generate interactive visualizations')
parser.add_argument('--static', action='store_true', help='Generate static visualizations')
parser.add_argument('--stats', action='store_true', help='Show knowledge graph statistics')
parser.add_argument('--concept-id', help='Analyze a specific concept', type=int)
parser.add_argument('--communities', action='store_true', help='Detect and analyze communities')
parser.add_argument('--centrality', action='store_true', help='Analyze concept centrality')
parser.add_argument('--output', help='Output file for analysis results (JSON)', type=str)
parser.add_argument('--source-type', help='Filter by source type')
parser.add_argument('--top-k', help='Top K results to consider', type=int, default=10)
parser.add_argument('--max-tokens-answer', help='Maximum tokens for answer', type=int, default=DEFAULT_MAX_TOKENS)
parser.add_argument('--max-tokens-context', help='Maximum tokens for context', type=int, default=4000)
parser.add_argument('--vector-weight', help='Weight for vector search (0-1)', type=float)
parser.add_argument('--keyword-weight', help='Weight for keyword search (0-1)', type=float)
parser.add_argument('--temperature', help='Temperature for generation', type=float, default=DEFAULT_TEMPERATURE)
parser.add_argument('--model', help='LLM model to use', default=DEFAULT_MODEL)
parser.add_argument('--stream', action='store_true', help='Stream the response')
parser.add_argument('--save', action='store_true', help='Save the response to file')
parser.add_argument('--output', help='Output file for the response')
parser.add_argument('--knowledge', action='store_true', help='Build or update the knowledge base')
parser.add_argument('--embeddings', action='store_true', help='Generate and index embeddings')
parser.add_argument('--papers', action='store_true', help='Collect and process research papers')
parser.add_argument('--visualize', action='store_true', help='Run visualization tools')
parser.add_argument('--all', action='store_true', help='Run all main operations')
parser.add_argument('--transcribe', action='store_true', help='Run audio extraction and transcription')
parser.add_argument('--batch-size', help='Batch size for transcription', type=int, default=16)
parser.add_argument('--extraction-workers', help='Number of parallel audio extraction workers', type=int, default=4)
parser.add_argument('--auto-batch-size', action='store_true', help='Automatically determine optimal batch size')
parser.add_argument('--download-papers', action='store_true', help='Download papers without processing')
parser.add_argument('--process-papers', action='store_true', help='Process previously downloaded papers')
parser.add_argument('--max-papers', help='Maximum number of papers to process', type=int, default=50)
parser.add_argument('--paper-url', help='Download a single paper from the provided URL', type=str)
parser.add_argument('--vector', action='store_true', help='Test vector search')
parser.add_argument('--keyword', action='store_true', help='Test keyword search')
parser.add_argument('--hybrid', action='store_true', help='Test hybrid search')
parser.add_argument('--compare', action='store_true', help='Compare all search methods')
parser.add_argument('--custom-query', help='Run tests with a custom query')
parser.add_argument('--top-k', help='Number of results to return', type=int, default=5)
parser.add_argument('--vector-weight', help='Weight for vector search (0-1)', type=float)
parser.add_argument('--keyword-weight', help='Weight for keyword search (0-1)', type=float)
parser.add_argument('--adaptive', action='store_true', help='Use adaptive weighting based on query')
parser.add_argument('--in-memory', action='store_true', help='Use in-memory indexing for vector search')
parser.add_argument('--detailed', action='store_true', help='Show detailed results')
parser.add_argument('--top-k', help='Number of results to show', type=int, default=5)
parser.add_argument('--source-type', help='Filter by source type')
parser.add_argument('--create-index', action='store_true', help='Create in-memory index before searching')
================================================================================
# API ENDPOINTS
================================================================================
## File: Instagram-Scraper/api/api.py
GET /health
Handler: health_check
Description: API endpoint for health check
POST /search
Handler: search
Description: API endpoint for search
POST /answer
Handler: answer
Description: API endpoint for generating answers
GET /answer/stream
Handler: answer_stream
Description: API endpoint for streaming answer generation
POST /feedback
Handler: save_feedback
Description: API endpoint for saving user feedback
## File: Instagram-Scraper/api/api_knowledge.py
GET /concepts/search
Handler: search_concepts
Description: API endpoint to search concepts
GET /concepts/<int:concept_id>
Handler: get_concept
Description: API endpoint to get concept details
GET /content/<int:content_id>
Handler: get_content
Description: API endpoint to get content details
GET /kg/stats
Handler: knowledge_graph_stats
Description: API endpoint to get knowledge graph statistics
## File: Instagram-Scraper/api/swagger.py
GET /api/swagger.json
Handler: swagger_json
Description: Return Swagger specification
## File: Instagram-Scraper/app.py
GET /
Handler: index
Description: Home page with search interface
GET /search
Handler: search
Description: Search interface page
GET /chat
Handler: chat
Description: Chat interface with RAG assistant
GET /concepts
Handler: concepts
Description: Concepts explorer page
GET /content/<int:content_id>
Handler: content_details
Description: Content details page
GET /video/<account>/<shortcode>
Handler: video
Description: Legacy video detail page - redirects to content page if possible
GET /about
Handler: about
Description: About page
GET /stats
Handler: stats
Description: Legacy statistics page - redirects to admin dashboard
GET /media/<path:path>
Handler: media
Description: Serve media files
## File: Instagram-Scraper/evaluation/dashboard.py
GET /
Handler: evaluation_dashboard
Description: Main evaluation dashboard page
GET /retrieval
Handler: retrieval_dashboard
Description: Retrieval metrics dashboard page
GET /answer-quality
Handler: answer_quality_dashboard
Description: Answer quality dashboard page
GET /datasets
Handler: datasets_dashboard
Description: Test datasets dashboard page
GET /api/test-results
Handler: test_results
Description: Get test results for dashboard
GET /api/test-result/<int:result_id>
Handler: test_result_detail
Description: Get detailed test result
GET /api/metrics/summary
Handler: metrics_summary
Description: Get summary metrics for dashboard
GET /api/datasets
Handler: test_datasets
Description: Get test datasets
GET /api/dataset/<int:dataset_id>
Handler: dataset_detail
Description: Get detailed dataset information
GET /api/answer-evaluations
Handler: answer_evaluations
Description: Get answer evaluations
GET /api/answer-evaluation/<int:eval_id>
Handler: answer_evaluation_detail
Description: Get detailed answer evaluation
## File: Instagram-Scraper/run.py
GET /
Handler: redirect_to_evaluation
================================================================================
# DATABASE SCHEMA
================================================================================
## Tables
### concepts
| Column | Type | Constraints |
|--------|------|-------------|
| id | INTEGER | PRIMARY KEY |
| name | TEXT | |
| description | TEXT | |
| category | TEXT | |
| first_seen_date | TEXT | |
| last_updated | TEXT | |
| reference_count | INTEGER | |
### concept_relationships
| Column | Type | Constraints |
|--------|------|-------------|
| id | INTEGER | PRIMARY KEY |
| source_concept_id | INTEGER | |
| target_concept_id | INTEGER | |
| relationship_type | TEXT | |
| first_seen_date | TEXT | |
| last_updated | TEXT | |
| reference_count | INTEGER | |
| confidence_score | REAL | |
| FOREIGN | KEY(source_concept_id) | REFERENCES concepts(id) |
| FOREIGN | KEY(target_concept_id) | REFERENCES concepts(id) |
### content_concepts
| Column | Type | Constraints |
|--------|------|-------------|
| id | INTEGER | PRIMARY KEY |
| content_id | INTEGER | |
| concept_id | INTEGER | |
| importance | TEXT | |
| date_extracted | TEXT | |
| FOREIGN | KEY(content_id) | REFERENCES ai_content(id) |
| FOREIGN | KEY(concept_id) | REFERENCES concepts(id) |
### search_query_log
| Column | Type | Constraints |
|--------|------|-------------|
| id | INTEGER | PRIMARY KEY |
| query | TEXT | |
| vector_weight | REAL | |
| keyword_weight | REAL | |
| search_type | TEXT | |
| source_type | TEXT | |
| result_count | INTEGER | |
| top_result_ids | TEXT | |
| JSON | array | |
| query_features | TEXT | |
### search_feedback
| Column | Type | Constraints |
|--------|------|-------------|
| id | INTEGER | PRIMARY KEY |
| query_log_id | INTEGER | |
| content_id | INTEGER | |
| feedback_score | INTEGER | |
| 5 | rating | |
| feedback_text | TEXT | |
| timestamp | TEXT | |
| FOREIGN | KEY(query_log_id) | REFERENCES search_query_log(id) |
### weight_patterns
| Column | Type | Constraints |
|--------|------|-------------|
| id | INTEGER | PRIMARY KEY |
| pattern_name | TEXT | |
| query_pattern | TEXT | |
| JSON | of | |
| keyword_weight | REAL | |
| positive_feedback_count | INTEGER | |
| negative_feedback_count | INTEGER | |
| last_updated | TEXT | |
| confidence_score | REAL | |
### videos
| Column | Type | Constraints |
|--------|------|-------------|
| id | INTEGER | PRIMARY KEY |
| shortcode | TEXT | |
| account | TEXT | |
| filename | TEXT | |
| caption | TEXT | |
| transcript | TEXT | |
| summary | TEXT | |
| timestamp | TEXT | |
| download_date | TEXT | |
| url | TEXT | |
| likes | INTEGER | |
| comments | INTEGER | |
| word_count | INTEGER | |
| duration_seconds | INTEGER | |
| key_phrases | TEXT | |
### tags
| Column | Type | Constraints |
|--------|------|-------------|
| id | INTEGER | PRIMARY KEY |
| video_id | INTEGER | |
| tag | TEXT | |
| FOREIGN | KEY | REFERENCES videos(id) |
## Relationships
| From Table | From Column | To Table | To Column |
|------------|-------------|----------|----------|
| concept_relationships | FOREIGN | concepts | id |
| content_concepts | FOREIGN | ai_content | id |
| content_concepts | FOREIGN | concepts | id |
| search_feedback | FOREIGN | search_query_log | id |
| tags | FOREIGN | videos | id |
================================================================================
# MODULE DEPENDENCIES
================================================================================
## Most Important Modules
| Module | Times Imported |
|--------|---------------|
| os | 32 |
| logging | 30 |
| sqlite3 | 24 |
| json | 22 |
| datetime.datetime | 21 |
| config | 19 |
| sys | 15 |
| time | 14 |
| typing.List | 10 |
| typing.Dict | 10 |
| typing.Optional | 10 |
| typing.Any | 9 |
| typing.Tuple | 8 |
| re | 7 |
| argparse | 7 |
| typing.Union | 7 |
| requests | 6 |
| flask.jsonify | 5 |
| flask.request | 4 |
| config.( | 4 |
## Module Import Graph
- Instagram-Scraper.add_missing_text_files
- imports argparse
- Instagram-Scraper.api.__init__
- imports .api.api_bp
- imports .api.setup_api_routes
- imports .api_knowledge.setup_knowledge_routes
- Instagram-Scraper.api.api
- imports config
- imports flask.Blueprint
- imports flask.Response
- imports flask.jsonify
- imports flask.request
- imports flask.stream_with_context
- imports sqlite3
- Instagram-Scraper.api.api_knowledge
- imports api.api.api_bp
- imports config
- imports flask.jsonify
- imports flask.request
- imports sqlite3
- Instagram-Scraper.api.swagger
- imports flask.Blueprint
- imports flask.jsonify
- imports flask_swagger_ui.get_swaggerui_blueprint
- Instagram-Scraper.app
- imports config.(
- imports flask.Flask
- imports flask.g
- imports flask.jsonify
- imports flask.redirect
- imports flask.render_template
- imports flask.request
- imports flask.send_from_directory
- imports flask.url_for
- imports functools.lru_cache
- imports sqlite3
- Instagram-Scraper.arxiv_collector
- imports Levenshtein
- imports PyPDF2
- imports bs4.BeautifulSoup
- imports config
- imports feedparser
- imports hashlib
- imports sqlite3
- imports urllib.parse.urljoin
- imports urllib.parse.urlparse
- Instagram-Scraper.chunking
- imports typing.Any
- imports typing.Dict
- imports typing.List
- Instagram-Scraper.concept_extractor
- imports anthropic
- imports config
- imports sqlite3
- Instagram-Scraper.context_builder
- imports chunking.chunk_text
- imports config
- imports embeddings.EmbeddingGenerator
- imports hybrid_search
- imports numpy
- imports sqlite3
- imports typing.Any
- imports typing.Dict
- imports typing.List
- imports typing.Optional
- imports typing.Set
- imports typing.Tuple
- imports typing.Union
- imports vector_search
- Instagram-Scraper.convert_jsonxz
- imports argparse
- imports config.DATA_DIR
- imports config.DOWNLOAD_DIR
- imports lzma
- imports pathlib.Path
- imports subprocess
- Instagram-Scraper.db_migration
- imports config
- imports sqlite3
- Instagram-Scraper.downloader
- imports config.(
- imports instaloader
- imports random
- imports socket
- imports sqlite3
- imports urllib.parse.parse_qs
- imports urllib.parse.urlparse
- imports urllib3
- Instagram-Scraper.embeddings
- imports chunking.chunk_text
- imports chunking.prepare_content_for_embedding
- imports config
- imports numpy
- imports pickle
- imports sqlite3
- imports typing.Any
- imports typing.Dict
- imports typing.List
- imports typing.Optional
- imports typing.Tuple
- imports typing.Union
- Instagram-Scraper.evaluation.answer_evaluator
- imports config
- imports sqlite3
- Instagram-Scraper.evaluation.dashboard
- imports config
- imports flask.Blueprint
- imports flask.jsonify
- imports flask.redirect
- imports flask.render_template
- imports flask.request
- imports flask.url_for
- imports sqlite3
- Instagram-Scraper.evaluation.retrieval_metrics
- imports config
- imports numpy
- imports sqlite3
- Instagram-Scraper.evaluation.test_queries
- imports config
- imports random
- imports sqlite3
- Instagram-Scraper.evaluation.test_runner
- imports config
- imports evaluation.answer_evaluator.AnswerEvaluator
- imports evaluation.retrieval_metrics.RetrievalEvaluator
- imports sqlite3
- Instagram-Scraper.generate_embeddings
- imports argparse
- imports chunking.chunk_text
- imports chunking.prepare_content_for_embedding
- imports config
- imports embeddings.EmbeddingGenerator
- imports sqlite3
- imports typing.Any
- imports typing.Dict
- imports typing.List
- imports typing.Optional
- imports typing.Tuple
- imports typing.Union
- Instagram-Scraper.github_collector
- imports base64
- imports config
- imports sqlite3
- Instagram-Scraper.hybrid_search
- imports config
- imports embeddings.EmbeddingGenerator
- imports sqlite3
- imports typing.Any
- imports typing.Dict
- imports typing.List
- imports typing.Optional
- imports typing.Tuple
- imports typing.Union
- imports vector_search.enrich_search_results
- imports vector_search.search_by_text
- Instagram-Scraper.indexer
- imports config.(
- imports glob
- imports sqlite3
- imports tqdm.tqdm
- Instagram-Scraper.init_db
- imports config.DATA_DIR
- imports config.DB_PATH
- imports sqlite3
- Instagram-Scraper.knowledge_graph
- imports config
- imports sqlite3
- imports typing.Any
- imports typing.Dict
- imports typing.List
- imports typing.Optional
- imports typing.Set
- imports typing.Tuple
- imports typing.Union
- Instagram-Scraper.llm_integration
- imports argparse
- imports config
- imports context_builder.ContextBuilder
- imports typing.Any
- imports typing.Callable
- imports typing.Dict
- imports typing.Generator
- imports typing.List
- imports typing.Optional
- imports typing.Union
- Instagram-Scraper.mistral_ocr
- imports PyPDF2.PdfReader
- imports PyPDF2.PdfWriter
- imports base64
- imports io.BytesIO
- imports typing.Optional
- imports typing.Tuple
- Instagram-Scraper.run
- imports app.app
- imports argparse
- imports config
- imports config.DATA_DIR
- imports downloader
- imports indexer
- imports sqlite3
- imports summarizer
- imports transcriber
- Instagram-Scraper.summarizer
- imports anthropic.Anthropic
- imports anthropic.types.message_create_params.MessageCreateParamsNonStreaming
- imports anthropic.types.messages.batch_create_params.Request
- imports config.DATA_DIR
- imports config.DB_PATH
- imports config.TRANSCRIPT_DIR
- imports sqlite3
- imports uuid
- Instagram-Scraper.test_db
- imports sqlite3
- Instagram-Scraper.test_proxy
- imports urllib3
- Instagram-Scraper.test_vector_search
- imports argparse
- imports typing.Any
- imports typing.Dict
- imports typing.List
- imports typing.Optional
- Instagram-Scraper.transcriber
- imports argparse
- imports concurrent.futures
- imports concurrent.futures.ThreadPoolExecutor
- imports config.(
- imports glob
- imports signal
- imports subprocess
- imports torch
- imports tqdm.tqdm
- imports typing.Dict
- imports typing.List
- imports typing.Optional
- imports typing.Tuple
- imports whisper
- Instagram-Scraper.vector_search
- imports config
- imports embeddings.EmbeddingGenerator
- imports numpy
- imports pickle
- imports sqlite3
- imports typing.Any
- imports typing.Dict
- imports typing.List
- imports typing.Optional
- imports typing.Tuple
- imports typing.Union
================================================================================
# FUNCTION CALLS
================================================================================
## Most Called Functions
| Function | Times Called |
|----------|-------------|
| logger.error | 126 |
| str | 114 |
| logger.info | 113 |
| len | 78 |
| cursor.execute | 69 |
| conn.cursor | 68 |
| conn.close | 60 |
| sqlite3.connect | 53 |
| logger.warning | 53 |
| open | 43 |
| cursor.fetchone | 40 |
| cursor.fetchall | 36 |
| datetime.now | 35 |
| os.makedirs | 33 |
| enumerate | 29 |
| conn.commit | 23 |
| json.dump | 20 |
| time.sleep | 20 |
| json.load | 19 |
| jsonify | 17 |
================================================================================
# CODE COMPLEXITY
================================================================================
## Most Complex Functions
| Function | Complexity | File | Line |
|----------|------------|------|------|
| migrate_database | 34 | None | 18 |
| process_arxiv_papers | 33 | None | 777 |
| download_from_instagram | 31 | None | 426 |
| process_posts | 28 | None | 706 |
| run_retrieval_tests | 25 | None | 76 |
| run_retrieval_tests | 25 | None | 76 |
| parse_sections | 24 | None | 258 |
| visualize_interactive | 24 | None | 1234 |
| visualize_interactive | 24 | None | 1234 |
| process_videos | 24 | None | 241 |
| download_paper_from_url | 23 | None | 311 |
| main | 22 | None | 39 |
| download_papers_only | 21 | None | 1109 |
| get_paginated_posts | 20 | None | 592 |
| visualize_with_matplotlib | 20 | None | 1095 |
| visualize_with_matplotlib | 20 | None | 1095 |
| main | 19 | None | 358 |
| batch_process_pdfs | 18 | None | 1251 |
| get_proxy | 18 | None | 141 |
| run_hybrid_search | 18 | None | 320 |
### Complexity Guidelines
Cyclomatic complexity is a measure of the number of linearly independent paths through a program's source code:
- 1-5: Low complexity - Simple, well-structured code
- 6-10: Medium complexity - Moderately complex code, still maintainable
- 11-20: High complexity - Complex code that may need refactoring
- 21+: Very high complexity - Code that should be refactored
### Complexity Distribution
- Low complexity (1-5): 0 functions
- Medium complexity (6-10): 0 functions
- High complexity (11-20): 51 functions
- Very high complexity (21+): 13 functions
================================================================================
# TEMPLATE HIERARCHY
================================================================================
answer_quality.html extends evaluation/layout.html
Blocks: content, page_title, page_actions, scripts, title
dashboard.html extends evaluation/layout.html
Blocks: content, page_title, page_actions, scripts, title
datasets.html extends evaluation/layout.html
Blocks: content, page_title, page_actions, scripts, title
retrieval_dashboard.html extends evaluation/layout.html
Blocks: content, page_title, page_actions, scripts, title
================================================================================
# FILE: Instagram-Scraper/add_missing_text_files.py
================================================================================
# Key imports:
# import os
# import json
# import logging
# import re
# from datetime import datetime
# ... and 1 more imports
# Functions:
def normalize_filename(filename) [complexity: 3 - low]: "Normalize filename for comparison by removing extension and"
def main() [complexity: 22 - high]: "Main function to compare PDF and text files and update the pending list."
================================================================================
# FILE: Instagram-Scraper/api/api.py
================================================================================
# Key imports:
# from flask import Blueprint, request, jsonify, Response, stream_with_context
import logging
from datetime import datetime
import sys
import os
import json
import sqlite3
# Add parent directory to path to allow imports from main package
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import config
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('api')
# Create Blueprint
api_bp = Blueprint('api', __name__, url_prefix='/api/v1')
def setup_api_routes():
"""Setup additional routes for the API blueprint"""
pass
@api_bp.route('/health', methods=['GET'])
def health_check():
"""API endpoint for health check"""
return jsonify({
'status': 'ok',
'timestamp': datetime.now().isoformat(),
'version': '1.0.0'
})
@api_bp.route('/search', methods=['POST'])
def search():
"""API endpoint for search"""
# Parse request
data = request.json
if not data or 'query' not in data:
return jsonify({'error': 'Query parameter is required'}), 400
# Extract parameters
query = data['query']
search_type = data.get('search_type', 'hybrid')
top_k = data.get('top_k', 10)
vector_weight = data.get('vector_weight')
keyword_weight = data.get('keyword_weight')
source_type = data.get('source_type')
page = data.get('page', 1)
logger.info(f"API search request: {query}")
try:
# Import locally to avoid circular imports
from run import run_hybrid_search, run_vector_search
# Flask routes:
@api_bp.route('/health', methods=[GET])
def health_check(): "API endpoint for health check"
@api_bp.route('/search', methods=[POST])
def search(): "API endpoint for search"
@api_bp.route('/answer', methods=[POST])
def answer(): "API endpoint for generating answers"
@api_bp.route('/answer/stream', methods=[GET])
def answer_stream(): "API endpoint for streaming answer generation"
@api_bp.route('/feedback', methods=[POST])
def save_feedback(): "API endpoint for saving user feedback"
# Functions:
def setup_api_routes() [complexity: 1 - low]: "Setup additional routes for the API blueprint"
def log_search_query(query, search_type, results_count) [complexity: 2 - low]: "Log search query to database"
def get_last_query_id() [complexity: 2 - low]: "Get the ID of the last logged query"
def generate() [complexity: 5 - low]
================================================================================
# FILE: Instagram-Scraper/api/api_knowledge.py
================================================================================
# Key imports:
# from flask import request, jsonify
import logging
import sqlite3
import sys
import os
# Add parent directory to path to allow imports from main package
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import config
from api.api import api_bp
logger = logging.getLogger('api.knowledge')
def setup_knowledge_routes():
"""Setup knowledge graph and content routes for the API blueprint"""
pass
@api_bp.route('/concepts/search', methods=['GET'])
def search_concepts():
"""API endpoint to search concepts"""
query = request.args.get('q', '')
category = request.args.get('category')
limit = int(request.args.get('limit', 10))
if not query:
return jsonify({"error": "Query parameter 'q' is required"}), 400
try:
# Import knowledge graph module (using try/except to handle possible import errors)
try:
from knowledge_graph import KnowledgeGraph
graph = KnowledgeGraph()
results = graph.search_concepts(query, limit=limit, category=category)
return jsonify({
"query": query,
"results": results
})
except ImportError:
# If knowledge_graph module is not available, fallback to direct DB query
conn = sqlite3.connect(config.DB_PATH)
cursor = conn.cursor()
# Build query
base_query = """
SELECT id, name, category, importance, confidence
FROM concepts
WHERE name LIKE ?
"""
params = [f"%{query}%"]
if category:
base_query += " AND category = ?"
params.append(category)
base_query += " ORDER BY importance DESC LIMIT ?"
params.append(limit)
cursor.execute(base_query, params)
results = []
for row in cursor.fetchall():
results.append({
'id': row[0],
'name': row[1],
'category': row[2],
'importance': row[3],
'confidence': row[4]
})
conn.close()
return jsonify({
"query": query,
"results": results
})
except Exception as e:
logger.error(f"Error in concept search API: {str(e)}")
return jsonify({'error': str(e)}), 500
@api_bp.route('/concepts/<int:concept_id>', methods=['GET'])
def get_concept(concept_id):
"""API endpoint to get concept details"""
try:
try:
from knowledge_graph import KnowledgeGraph
graph = KnowledgeGraph()
concept = graph.get_concept(concept_id=concept_id)
if not concept:
return jsonify({"error": "Concept not found"}), 404
return jsonify(concept)
except ImportError:
# Fallback to direct DB query
conn = sqlite3.connect(config.DB_PATH)
cursor = conn.cursor()
# Get concept details