InstagramFollowerAnalysis 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. instagramfolloweranalysis-0.2.0/CONTRIBUTING.md +23 -0
  2. instagramfolloweranalysis-0.2.0/LICENSE +21 -0
  3. instagramfolloweranalysis-0.2.0/MANIFEST.in +4 -0
  4. instagramfolloweranalysis-0.2.0/PKG-INFO +168 -0
  5. instagramfolloweranalysis-0.2.0/README.md +154 -0
  6. instagramfolloweranalysis-0.2.0/TEST_RESULTS.txt +72 -0
  7. instagramfolloweranalysis-0.2.0/docs/DEMO.md +9 -0
  8. instagramfolloweranalysis-0.2.0/docs/QA.md +7 -0
  9. instagramfolloweranalysis-0.2.0/examples/demo.py +6 -0
  10. instagramfolloweranalysis-0.2.0/examples/export_shape.json +1 -0
  11. instagramfolloweranalysis-0.2.0/examples/followers.csv +4 -0
  12. instagramfolloweranalysis-0.2.0/examples/followers.json +1 -0
  13. instagramfolloweranalysis-0.2.0/examples/followers.txt +3 -0
  14. instagramfolloweranalysis-0.2.0/examples/followers_after.json +1 -0
  15. instagramfolloweranalysis-0.2.0/examples/following.json +1 -0
  16. instagramfolloweranalysis-0.2.0/main.py +4 -0
  17. instagramfolloweranalysis-0.2.0/pyproject.toml +26 -0
  18. instagramfolloweranalysis-0.2.0/setup.cfg +4 -0
  19. instagramfolloweranalysis-0.2.0/src/InstagramFollowerAnalysis.egg-info/PKG-INFO +168 -0
  20. instagramfolloweranalysis-0.2.0/src/InstagramFollowerAnalysis.egg-info/SOURCES.txt +28 -0
  21. instagramfolloweranalysis-0.2.0/src/InstagramFollowerAnalysis.egg-info/dependency_links.txt +1 -0
  22. instagramfolloweranalysis-0.2.0/src/InstagramFollowerAnalysis.egg-info/entry_points.txt +2 -0
  23. instagramfolloweranalysis-0.2.0/src/InstagramFollowerAnalysis.egg-info/requires.txt +3 -0
  24. instagramfolloweranalysis-0.2.0/src/InstagramFollowerAnalysis.egg-info/top_level.txt +1 -0
  25. instagramfolloweranalysis-0.2.0/src/igfollowchecker/__init__.py +4 -0
  26. instagramfolloweranalysis-0.2.0/src/igfollowchecker/__main__.py +2 -0
  27. instagramfolloweranalysis-0.2.0/src/igfollowchecker/cli.py +65 -0
  28. instagramfolloweranalysis-0.2.0/src/igfollowchecker/core.py +76 -0
  29. instagramfolloweranalysis-0.2.0/src/igfollowchecker/live.py +126 -0
  30. instagramfolloweranalysis-0.2.0/tests/test_package.py +121 -0
@@ -0,0 +1,23 @@
1
+ # Attended Topic Discussion Meeting
2
+ - [x] Tsz Ying CHENG
3
+ - [x] Chun Yin Alvin KWOK
4
+ - [x] Hong Yau LEUNG
5
+ - [x] Ching Yi LI
6
+ - [x] Yat Sang MAK
7
+
8
+ # Coding Contribution
9
+ - [x] Tsz Ying CHENG
10
+ - [x] Yat Sang MAK
11
+ # Coding Assistance
12
+ - [x] Hermes agent
13
+ - [x] Chun Yin Alvin KWOK
14
+ - [x] Hong Yau LEUNG
15
+ - [x] Ching Yi LI
16
+
17
+ # Presentation discussion
18
+ - [x] Tsz Ying CHENG
19
+ - [x] Chun Yin Alvin KWOK
20
+ - [x] Hong Yau LEUNG
21
+ - [x] Ching Yi LI
22
+ - [x] Yat Sang MAK
23
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 IGFollowChecker contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ include README.md LICENSE CONTRIBUTING.md TEST_RESULTS.txt main.py
2
+ recursive-include docs *.md
3
+ recursive-include examples *
4
+ recursive-include tests *.py
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.4
2
+ Name: InstagramFollowerAnalysis
3
+ Version: 0.2.0
4
+ Summary: Offline follower analysis with optional visible-browser collection
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/ismeseraphina/InstagramSentimentAnalysis
7
+ Project-URL: Repository, https://github.com/ismeseraphina/InstagramSentimentAnalysis
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: live
12
+ Requires-Dist: selenium<5,>=4.10; extra == "live"
13
+ Dynamic: license-file
14
+
15
+ ## CS1302A group project
16
+ IGFollowChecker 0.2.0
17
+
18
+ A local-first Python package for follower-list analysis, with optional visible
19
+ Chrome collection. No auto follow/unfollow, stealth options or credential export.
20
+ AI usage: Debugging code and organising tasks only
21
+
22
+ ## Motivation
23
+
24
+ Comparing follower lists manually is tedious. A live-only browser script also
25
+ couples data collection, authentication and analysis. This package separates
26
+ collection from deterministic, reusable list comparison.
27
+
28
+ ## Contribution / innovation
29
+
30
+ The contribution is a focused workflow: normalized inputs, explicit file formats,
31
+ deterministic reports, snapshot comparisons and an optional browser collector
32
+ whose completeness limitations are explicit. Set difference is standard, not a
33
+ new algorithm. We do not claim this is the first follower comparison tool.
34
+
35
+ ## Install from this complete project
36
+
37
+ Python 3.9+. In the folder containing pyproject.toml:
38
+
39
+ ```sh
40
+ python3 -m venv .venv
41
+ source .venv/bin/activate
42
+ python -m pip install -e .
43
+ python -m unittest discover -s tests -v
44
+ python examples/demo.py
45
+ ```
46
+
47
+ Windows: use `.venv\Scripts\activate`. For live functionality install:
48
+
49
+ ```sh
50
+ python -m pip install -e ".[live]"
51
+ ```
52
+
53
+ This installs Selenium as an optional dependency. Chrome and a graphical desktop
54
+ are needed. Selenium Manager handles driver discovery/setup and may download
55
+ components. Do not assume hosted JupyterHub can display a live browser.
56
+ Offline functions have no runtime third-party dependencies.
57
+
58
+ After an actual release, install the CONFIRMED distribution name from PyPI;
59
+ no existing publication is claimed in this document.
60
+
61
+ ## Offline CLI
62
+
63
+ ```sh
64
+ igfollowchecker analyze --followers examples/followers.json --following examples/following.json
65
+ igfollowchecker diff --before examples/followers.json --after examples/followers_after.json
66
+ igfollowchecker analyze --followers examples/followers.csv --following examples/following.json --json
67
+ ```
68
+
69
+ Expected analysis: 3 followers, 3 following, 2 mutuals; Charlie does not follow
70
+ back in the synthetic dataset; Dora is a fan; Alice and Bob are mutuals.
71
+ Add `--output report.json` to create JSON output. Existing files are not overwritten;
72
+ the parent directory must already exist. Exit codes: 0 success (including detected
73
+ differences), 2 error, 130 interrupted command. `python -m igfollowchecker` and
74
+ `python main.py` accept the same command arguments.
75
+
76
+ ## Live CLI
77
+
78
+ ```sh
79
+ igfollowchecker collect --username YOUR_ACCOUNT --output-dir private_data/session-01 --max-scrolls 30
80
+ ```
81
+
82
+ Use only authorized data and comply with platform rules. Log in yourself in
83
+ Chrome, complete verification manually, and return to Terminal. For each list,
84
+ YOU open the correct followers/following dialog, confirm it, and press Enter.
85
+ Do not interact during collection. Type SAVE at the final prompt to save.
86
+ 30 scrolls is a short smoke test, not a complete-list guarantee.
87
+
88
+ Output: followers.json, following.json, metadata.json in a NEW directory.
89
+ No passwords, cookies or session IDs are extracted/saved by this program. The
90
+ browser handles authentication normally; the program does not bypass challenges.
91
+
92
+ All captures have `completeness: unverified`. Visible profile links can be
93
+ incomplete or unexpected; a stable scroll is not proof of completeness. You
94
+ must confirm the correct dialog; this cannot be automatically guaranteed.
95
+ Zero collected links raises an error even for a genuinely empty list. Optional
96
+ `--expected-followers N --expected-following M` rejects count mismatches before
97
+ saving; equal counts still do not prove accuracy. Default pause 1.5 seconds,
98
+ maximum 200 scroll steps per list. Bounded collection does not guarantee freedom
99
+ from rate limits/account restrictions. Stop if access is blocked.
100
+
101
+ After reviewing files/metadata:
102
+
103
+ ```sh
104
+ igfollowchecker analyze --followers private_data/session-01/followers.json --following private_data/session-01/following.json
105
+ ```
106
+
107
+ The analyzer reads the supplied lists, NOT the sidecar metadata. Conclusions are
108
+ conditional on data accuracy. An interruption while saving may leave partial
109
+ files; metadata.json is written last. Offline does not mean encrypted.
110
+
111
+ ## Python API
112
+
113
+ ```python
114
+ from igfollowchecker import load_users, analyze, compare_snapshots
115
+ followers = load_users("examples/followers.json")
116
+ following = load_users("examples/following.json")
117
+ print(analyze(followers, following))
118
+ print(compare_snapshots(followers, {"alice", "dora", "erin"}))
119
+ ```
120
+
121
+ `normalize_username` strips surrounding whitespace, removes one leading @,
122
+ lowercases and checks 1-30 ASCII letters/digits/dots/underscores. This is syntax
123
+ validation, not proof of an account's existence. Duplicates collapse.
124
+ `load_users` returns a set; malformed input raises ValueError; file/encoding
125
+ errors propagate. `analyze` and `compare_snapshots` accept iterables of strings
126
+ (not a single string) and return JSON-serializable dictionaries, with sorted lists.
127
+
128
+ ## Supported input formats
129
+
130
+ - JSON string list: `["alice", "bob"]`.
131
+ - JSON object: `{"usernames": ["alice", "bob"]}`.
132
+ - JSON object list with non-empty `string_list_data` containing string `value`
133
+ fields, optionally wrapped in `relationships_following` or
134
+ `relationships_followers`. Exactly one supported wrapper key is allowed.
135
+ - CSV: unique headers including case-sensitive `username`; extra columns allowed.
136
+ Ragged records and blank usernames fail.
137
+ - TXT: one username per line; blank lines ignored.
138
+
139
+ Files use UTF-8 with optional BOM. See examples/export_shape.json (synthetic).
140
+ These are documented schemas, NOT a guarantee of compatibility with all/current
141
+ Instagram exports. HTML, ZIP and automatic discovery/merging of split export
142
+ files are unsupported. Test real authorized samples privately before claiming
143
+ support for their format.
144
+
145
+ ## Use cases and limitations
146
+
147
+ Analyze local account lists, compare dated snapshots, or teach set operations
148
+ with fictional social data. `not_following_back = following - followers`,
149
+ `fans = followers - following`, and `mutuals = intersection`.
150
+
151
+ A removed username only means absence in the later dataset, NOT proof of an
152
+ unfollow. Renames, account changes, timing and incomplete inputs matter. Compare
153
+ same-kind lists from the same account. No automatic repair, live account
154
+ verification, access-control bypass or encrypted storage is provided. Memory
155
+ grows with input size. Typical set operations are linear under ordinary hashing
156
+ assumptions; sorting output adds O(k log k).
157
+
158
+ ## Validation, teamwork and release
159
+
160
+ See TEST_RESULTS.txt for executed checks and untested parts. Real Instagram
161
+ login/collection was NOT tested here. A manual GitHub Actions workflow publishes to PyPI via Trusted Publishing.
162
+ See CONTRIBUTING.md, docs/DEMO.md and docs/QA.md.
163
+ Follow course AI disclosure rules and report actual team contributions honestly.
164
+
165
+ ## License
166
+
167
+ MIT for this supplied implementation; confirm ownership/permissions for any
168
+ existing material retained when integrating into a team repository.
@@ -0,0 +1,154 @@
1
+ ## CS1302A group project
2
+ IGFollowChecker 0.2.0
3
+
4
+ A local-first Python package for follower-list analysis, with optional visible
5
+ Chrome collection. No auto follow/unfollow, stealth options or credential export.
6
+ AI usage: Debugging code and organising tasks only
7
+
8
+ ## Motivation
9
+
10
+ Comparing follower lists manually is tedious. A live-only browser script also
11
+ couples data collection, authentication and analysis. This package separates
12
+ collection from deterministic, reusable list comparison.
13
+
14
+ ## Contribution / innovation
15
+
16
+ The contribution is a focused workflow: normalized inputs, explicit file formats,
17
+ deterministic reports, snapshot comparisons and an optional browser collector
18
+ whose completeness limitations are explicit. Set difference is standard, not a
19
+ new algorithm. We do not claim this is the first follower comparison tool.
20
+
21
+ ## Install from this complete project
22
+
23
+ Python 3.9+. In the folder containing pyproject.toml:
24
+
25
+ ```sh
26
+ python3 -m venv .venv
27
+ source .venv/bin/activate
28
+ python -m pip install -e .
29
+ python -m unittest discover -s tests -v
30
+ python examples/demo.py
31
+ ```
32
+
33
+ Windows: use `.venv\Scripts\activate`. For live functionality install:
34
+
35
+ ```sh
36
+ python -m pip install -e ".[live]"
37
+ ```
38
+
39
+ This installs Selenium as an optional dependency. Chrome and a graphical desktop
40
+ are needed. Selenium Manager handles driver discovery/setup and may download
41
+ components. Do not assume hosted JupyterHub can display a live browser.
42
+ Offline functions have no runtime third-party dependencies.
43
+
44
+ After an actual release, install the CONFIRMED distribution name from PyPI;
45
+ no existing publication is claimed in this document.
46
+
47
+ ## Offline CLI
48
+
49
+ ```sh
50
+ igfollowchecker analyze --followers examples/followers.json --following examples/following.json
51
+ igfollowchecker diff --before examples/followers.json --after examples/followers_after.json
52
+ igfollowchecker analyze --followers examples/followers.csv --following examples/following.json --json
53
+ ```
54
+
55
+ Expected analysis: 3 followers, 3 following, 2 mutuals; Charlie does not follow
56
+ back in the synthetic dataset; Dora is a fan; Alice and Bob are mutuals.
57
+ Add `--output report.json` to create JSON output. Existing files are not overwritten;
58
+ the parent directory must already exist. Exit codes: 0 success (including detected
59
+ differences), 2 error, 130 interrupted command. `python -m igfollowchecker` and
60
+ `python main.py` accept the same command arguments.
61
+
62
+ ## Live CLI
63
+
64
+ ```sh
65
+ igfollowchecker collect --username YOUR_ACCOUNT --output-dir private_data/session-01 --max-scrolls 30
66
+ ```
67
+
68
+ Use only authorized data and comply with platform rules. Log in yourself in
69
+ Chrome, complete verification manually, and return to Terminal. For each list,
70
+ YOU open the correct followers/following dialog, confirm it, and press Enter.
71
+ Do not interact during collection. Type SAVE at the final prompt to save.
72
+ 30 scrolls is a short smoke test, not a complete-list guarantee.
73
+
74
+ Output: followers.json, following.json, metadata.json in a NEW directory.
75
+ No passwords, cookies or session IDs are extracted/saved by this program. The
76
+ browser handles authentication normally; the program does not bypass challenges.
77
+
78
+ All captures have `completeness: unverified`. Visible profile links can be
79
+ incomplete or unexpected; a stable scroll is not proof of completeness. You
80
+ must confirm the correct dialog; this cannot be automatically guaranteed.
81
+ Zero collected links raises an error even for a genuinely empty list. Optional
82
+ `--expected-followers N --expected-following M` rejects count mismatches before
83
+ saving; equal counts still do not prove accuracy. Default pause 1.5 seconds,
84
+ maximum 200 scroll steps per list. Bounded collection does not guarantee freedom
85
+ from rate limits/account restrictions. Stop if access is blocked.
86
+
87
+ After reviewing files/metadata:
88
+
89
+ ```sh
90
+ igfollowchecker analyze --followers private_data/session-01/followers.json --following private_data/session-01/following.json
91
+ ```
92
+
93
+ The analyzer reads the supplied lists, NOT the sidecar metadata. Conclusions are
94
+ conditional on data accuracy. An interruption while saving may leave partial
95
+ files; metadata.json is written last. Offline does not mean encrypted.
96
+
97
+ ## Python API
98
+
99
+ ```python
100
+ from igfollowchecker import load_users, analyze, compare_snapshots
101
+ followers = load_users("examples/followers.json")
102
+ following = load_users("examples/following.json")
103
+ print(analyze(followers, following))
104
+ print(compare_snapshots(followers, {"alice", "dora", "erin"}))
105
+ ```
106
+
107
+ `normalize_username` strips surrounding whitespace, removes one leading @,
108
+ lowercases and checks 1-30 ASCII letters/digits/dots/underscores. This is syntax
109
+ validation, not proof of an account's existence. Duplicates collapse.
110
+ `load_users` returns a set; malformed input raises ValueError; file/encoding
111
+ errors propagate. `analyze` and `compare_snapshots` accept iterables of strings
112
+ (not a single string) and return JSON-serializable dictionaries, with sorted lists.
113
+
114
+ ## Supported input formats
115
+
116
+ - JSON string list: `["alice", "bob"]`.
117
+ - JSON object: `{"usernames": ["alice", "bob"]}`.
118
+ - JSON object list with non-empty `string_list_data` containing string `value`
119
+ fields, optionally wrapped in `relationships_following` or
120
+ `relationships_followers`. Exactly one supported wrapper key is allowed.
121
+ - CSV: unique headers including case-sensitive `username`; extra columns allowed.
122
+ Ragged records and blank usernames fail.
123
+ - TXT: one username per line; blank lines ignored.
124
+
125
+ Files use UTF-8 with optional BOM. See examples/export_shape.json (synthetic).
126
+ These are documented schemas, NOT a guarantee of compatibility with all/current
127
+ Instagram exports. HTML, ZIP and automatic discovery/merging of split export
128
+ files are unsupported. Test real authorized samples privately before claiming
129
+ support for their format.
130
+
131
+ ## Use cases and limitations
132
+
133
+ Analyze local account lists, compare dated snapshots, or teach set operations
134
+ with fictional social data. `not_following_back = following - followers`,
135
+ `fans = followers - following`, and `mutuals = intersection`.
136
+
137
+ A removed username only means absence in the later dataset, NOT proof of an
138
+ unfollow. Renames, account changes, timing and incomplete inputs matter. Compare
139
+ same-kind lists from the same account. No automatic repair, live account
140
+ verification, access-control bypass or encrypted storage is provided. Memory
141
+ grows with input size. Typical set operations are linear under ordinary hashing
142
+ assumptions; sorting output adds O(k log k).
143
+
144
+ ## Validation, teamwork and release
145
+
146
+ See TEST_RESULTS.txt for executed checks and untested parts. Real Instagram
147
+ login/collection was NOT tested here. A manual GitHub Actions workflow publishes to PyPI via Trusted Publishing.
148
+ See CONTRIBUTING.md, docs/DEMO.md and docs/QA.md.
149
+ Follow course AI disclosure rules and report actual team contributions honestly.
150
+
151
+ ## License
152
+
153
+ MIT for this supplied implementation; confirm ownership/permissions for any
154
+ existing material retained when integrating into a team repository.
@@ -0,0 +1,72 @@
1
+ Python: 3.12.14 (main, Nov 18 2026, 01:36:36) [GCC 15.2.0]
2
+ Source suite:
3
+ test_analysis (test_package.Tests.test_analysis) ... ok
4
+ test_bad_cli (test_package.Tests.test_bad_cli) ... ok
5
+ test_bad_csv (test_package.Tests.test_bad_csv) ... ok
6
+ test_bad_urls (test_package.Tests.test_bad_urls) ... ok
7
+ test_cli_json (test_package.Tests.test_cli_json) ... ok
8
+ test_csv (test_package.Tests.test_csv) ... ok
9
+ test_dialog_stopping (test_package.Tests.test_dialog_stopping) ... ok
10
+ test_diff (test_package.Tests.test_diff) ... ok
11
+ test_duplicates (test_package.Tests.test_duplicates) ... ok
12
+ test_empty (test_package.Tests.test_empty) ... ok
13
+ test_empty_dialog_error (test_package.Tests.test_empty_dialog_error) ... ok
14
+ test_export (test_package.Tests.test_export) ... ok
15
+ test_extension (test_package.Tests.test_extension) ... ok
16
+ test_invalid_json (test_package.Tests.test_invalid_json) ... ok
17
+ test_invalid_names (test_package.Tests.test_invalid_names) ... ok
18
+ test_json (test_package.Tests.test_json) ... ok
19
+ test_missing (test_package.Tests.test_missing) ... ok
20
+ test_no_mutation (test_package.Tests.test_no_mutation) ... ok
21
+ test_normalize (test_package.Tests.test_normalize) ... ok
22
+ test_output_and_no_overwrite (test_package.Tests.test_output_and_no_overwrite) ... ok
23
+ test_profile_url (test_package.Tests.test_profile_url) ... ok
24
+ test_txt_bom (test_package.Tests.test_txt_bom) ... ok
25
+ test_wrapper (test_package.Tests.test_wrapper) ... ok
26
+ test_wrong_iterable (test_package.Tests.test_wrong_iterable) ... ok
27
+
28
+ ----------------------------------------------------------------------
29
+ Ran 24 tests in 0.010s
30
+
31
+ OK
32
+
33
+ Wheel and sdist built offline with installed setuptools backend.
34
+ Fresh isolated venv, wheel installed with --no-index --no-deps, tested outside repo:
35
+ test_analysis (test_package.Tests.test_analysis) ... ok
36
+ test_bad_cli (test_package.Tests.test_bad_cli) ... ok
37
+ test_bad_csv (test_package.Tests.test_bad_csv) ... ok
38
+ test_bad_urls (test_package.Tests.test_bad_urls) ... ok
39
+ test_cli_json (test_package.Tests.test_cli_json) ... ok
40
+ test_csv (test_package.Tests.test_csv) ... ok
41
+ test_dialog_stopping (test_package.Tests.test_dialog_stopping) ... ok
42
+ test_diff (test_package.Tests.test_diff) ... ok
43
+ test_duplicates (test_package.Tests.test_duplicates) ... ok
44
+ test_empty (test_package.Tests.test_empty) ... ok
45
+ test_empty_dialog_error (test_package.Tests.test_empty_dialog_error) ... ok
46
+ test_export (test_package.Tests.test_export) ... ok
47
+ test_extension (test_package.Tests.test_extension) ... ok
48
+ test_invalid_json (test_package.Tests.test_invalid_json) ... ok
49
+ test_invalid_names (test_package.Tests.test_invalid_names) ... ok
50
+ test_json (test_package.Tests.test_json) ... ok
51
+ test_missing (test_package.Tests.test_missing) ... ok
52
+ test_no_mutation (test_package.Tests.test_no_mutation) ... ok
53
+ test_normalize (test_package.Tests.test_normalize) ... ok
54
+ test_output_and_no_overwrite (test_package.Tests.test_output_and_no_overwrite) ... ok
55
+ test_profile_url (test_package.Tests.test_profile_url) ... ok
56
+ test_txt_bom (test_package.Tests.test_txt_bom) ... ok
57
+ test_wrapper (test_package.Tests.test_wrapper) ... ok
58
+ test_wrong_iterable (test_package.Tests.test_wrong_iterable) ... ok
59
+
60
+ ----------------------------------------------------------------------
61
+ Ran 24 tests in 0.010s
62
+
63
+ OK
64
+
65
+ Installed demo:
66
+ {'counts': {'followers': 3, 'following': 3, 'mutuals': 2}, 'not_following_back': ['charlie'], 'fans': ['dora'], 'mutuals': ['alice', 'bob']}
67
+ {'added': ['erin'], 'removed': ['bob'], 'unchanged_count': 2}
68
+
69
+ Installed collect --help: exit 0.
70
+ Offline tests passed without Selenium installed in verification venv.
71
+ Live helper tests use fake drivers, not Instagram.
72
+ NOT tested: Selenium installation, real Chrome/login/Instagram, Python 3.9 runtime, GitHub Actions, course JupyterHub, twine check or PyPI publication/name availability.
@@ -0,0 +1,9 @@
1
+ # 1-minute demo script
2
+
3
+ Offline only, so the demo never depends on Instagram login.
4
+
5
+ 1. (0-10s) Problem: comparing follower lists by hand is slow; we separate collection from reusable offline analysis.
6
+ 2. (10-20s) Show the PyPI page and the repo link, then `pip install InstagramFollowerAnalysis`.
7
+ 3. (20-40s) `igfollowchecker analyze --followers examples/followers.json --following examples/following.json`
8
+ 4. (40-50s) `igfollowchecker diff --before examples/followers.json --after examples/followers_after.json`
9
+ 5. (50-60s) Innovation is the workflow (normalised inputs, snapshots, optional manual-login collector), not set difference. Limit: input completeness is unverified.
@@ -0,0 +1,7 @@
1
+ # Likely Q&A
2
+
3
+ - Why not just a script? Reusable package, tested parsers (24 tests), stable CLI and Python API.
4
+ - Is live collection safe? No credentials are read or stored; the user logs in manually and confirms each list. No auto follow/unfollow.
5
+ - Is the result complete? Not guaranteed; metadata marks `completeness: unverified`.
6
+ - Why a PyPI name with a suffix? The plain name is likely taken; the import name stays `igfollowchecker`.
7
+ - What is original? Workflow integration and snapshot diffing, stated honestly.
@@ -0,0 +1,6 @@
1
+ from pathlib import Path
2
+ from igfollowchecker import analyze, compare_snapshots, load_users
3
+ p = Path(__file__).resolve().parent
4
+ followers = load_users(p / "followers.json")
5
+ print(analyze(followers, load_users(p / "following.json")))
6
+ print(compare_snapshots(followers, load_users(p / "followers_after.json")))
@@ -0,0 +1 @@
1
+ {"relationships_following":[{"string_list_data":[{"value":"alice"}]}]}
@@ -0,0 +1,4 @@
1
+ username
2
+ alice
3
+ bob
4
+ dora
@@ -0,0 +1 @@
1
+ ["alice", "bob", "dora"]
@@ -0,0 +1,3 @@
1
+ alice
2
+ bob
3
+ dora
@@ -0,0 +1 @@
1
+ ["alice", "dora", "erin"]
@@ -0,0 +1 @@
1
+ {"usernames":["alice", "bob", "charlie"]}
@@ -0,0 +1,4 @@
1
+ from igfollowchecker.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "InstagramFollowerAnalysis"
7
+ version = "0.2.0"
8
+ description = "Offline follower analysis with optional visible-browser collection"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = []
14
+
15
+ [project.optional-dependencies]
16
+ live = ["selenium>=4.10,<5"]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/ismeseraphina/InstagramSentimentAnalysis"
20
+ Repository = "https://github.com/ismeseraphina/InstagramSentimentAnalysis"
21
+
22
+ [project.scripts]
23
+ igfollowchecker = "igfollowchecker.cli:main"
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.4
2
+ Name: InstagramFollowerAnalysis
3
+ Version: 0.2.0
4
+ Summary: Offline follower analysis with optional visible-browser collection
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/ismeseraphina/InstagramSentimentAnalysis
7
+ Project-URL: Repository, https://github.com/ismeseraphina/InstagramSentimentAnalysis
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: live
12
+ Requires-Dist: selenium<5,>=4.10; extra == "live"
13
+ Dynamic: license-file
14
+
15
+ ## CS1302A group project
16
+ IGFollowChecker 0.2.0
17
+
18
+ A local-first Python package for follower-list analysis, with optional visible
19
+ Chrome collection. No auto follow/unfollow, stealth options or credential export.
20
+ AI usage: Debugging code and organising tasks only
21
+
22
+ ## Motivation
23
+
24
+ Comparing follower lists manually is tedious. A live-only browser script also
25
+ couples data collection, authentication and analysis. This package separates
26
+ collection from deterministic, reusable list comparison.
27
+
28
+ ## Contribution / innovation
29
+
30
+ The contribution is a focused workflow: normalized inputs, explicit file formats,
31
+ deterministic reports, snapshot comparisons and an optional browser collector
32
+ whose completeness limitations are explicit. Set difference is standard, not a
33
+ new algorithm. We do not claim this is the first follower comparison tool.
34
+
35
+ ## Install from this complete project
36
+
37
+ Python 3.9+. In the folder containing pyproject.toml:
38
+
39
+ ```sh
40
+ python3 -m venv .venv
41
+ source .venv/bin/activate
42
+ python -m pip install -e .
43
+ python -m unittest discover -s tests -v
44
+ python examples/demo.py
45
+ ```
46
+
47
+ Windows: use `.venv\Scripts\activate`. For live functionality install:
48
+
49
+ ```sh
50
+ python -m pip install -e ".[live]"
51
+ ```
52
+
53
+ This installs Selenium as an optional dependency. Chrome and a graphical desktop
54
+ are needed. Selenium Manager handles driver discovery/setup and may download
55
+ components. Do not assume hosted JupyterHub can display a live browser.
56
+ Offline functions have no runtime third-party dependencies.
57
+
58
+ After an actual release, install the CONFIRMED distribution name from PyPI;
59
+ no existing publication is claimed in this document.
60
+
61
+ ## Offline CLI
62
+
63
+ ```sh
64
+ igfollowchecker analyze --followers examples/followers.json --following examples/following.json
65
+ igfollowchecker diff --before examples/followers.json --after examples/followers_after.json
66
+ igfollowchecker analyze --followers examples/followers.csv --following examples/following.json --json
67
+ ```
68
+
69
+ Expected analysis: 3 followers, 3 following, 2 mutuals; Charlie does not follow
70
+ back in the synthetic dataset; Dora is a fan; Alice and Bob are mutuals.
71
+ Add `--output report.json` to create JSON output. Existing files are not overwritten;
72
+ the parent directory must already exist. Exit codes: 0 success (including detected
73
+ differences), 2 error, 130 interrupted command. `python -m igfollowchecker` and
74
+ `python main.py` accept the same command arguments.
75
+
76
+ ## Live CLI
77
+
78
+ ```sh
79
+ igfollowchecker collect --username YOUR_ACCOUNT --output-dir private_data/session-01 --max-scrolls 30
80
+ ```
81
+
82
+ Use only authorized data and comply with platform rules. Log in yourself in
83
+ Chrome, complete verification manually, and return to Terminal. For each list,
84
+ YOU open the correct followers/following dialog, confirm it, and press Enter.
85
+ Do not interact during collection. Type SAVE at the final prompt to save.
86
+ 30 scrolls is a short smoke test, not a complete-list guarantee.
87
+
88
+ Output: followers.json, following.json, metadata.json in a NEW directory.
89
+ No passwords, cookies or session IDs are extracted/saved by this program. The
90
+ browser handles authentication normally; the program does not bypass challenges.
91
+
92
+ All captures have `completeness: unverified`. Visible profile links can be
93
+ incomplete or unexpected; a stable scroll is not proof of completeness. You
94
+ must confirm the correct dialog; this cannot be automatically guaranteed.
95
+ Zero collected links raises an error even for a genuinely empty list. Optional
96
+ `--expected-followers N --expected-following M` rejects count mismatches before
97
+ saving; equal counts still do not prove accuracy. Default pause 1.5 seconds,
98
+ maximum 200 scroll steps per list. Bounded collection does not guarantee freedom
99
+ from rate limits/account restrictions. Stop if access is blocked.
100
+
101
+ After reviewing files/metadata:
102
+
103
+ ```sh
104
+ igfollowchecker analyze --followers private_data/session-01/followers.json --following private_data/session-01/following.json
105
+ ```
106
+
107
+ The analyzer reads the supplied lists, NOT the sidecar metadata. Conclusions are
108
+ conditional on data accuracy. An interruption while saving may leave partial
109
+ files; metadata.json is written last. Offline does not mean encrypted.
110
+
111
+ ## Python API
112
+
113
+ ```python
114
+ from igfollowchecker import load_users, analyze, compare_snapshots
115
+ followers = load_users("examples/followers.json")
116
+ following = load_users("examples/following.json")
117
+ print(analyze(followers, following))
118
+ print(compare_snapshots(followers, {"alice", "dora", "erin"}))
119
+ ```
120
+
121
+ `normalize_username` strips surrounding whitespace, removes one leading @,
122
+ lowercases and checks 1-30 ASCII letters/digits/dots/underscores. This is syntax
123
+ validation, not proof of an account's existence. Duplicates collapse.
124
+ `load_users` returns a set; malformed input raises ValueError; file/encoding
125
+ errors propagate. `analyze` and `compare_snapshots` accept iterables of strings
126
+ (not a single string) and return JSON-serializable dictionaries, with sorted lists.
127
+
128
+ ## Supported input formats
129
+
130
+ - JSON string list: `["alice", "bob"]`.
131
+ - JSON object: `{"usernames": ["alice", "bob"]}`.
132
+ - JSON object list with non-empty `string_list_data` containing string `value`
133
+ fields, optionally wrapped in `relationships_following` or
134
+ `relationships_followers`. Exactly one supported wrapper key is allowed.
135
+ - CSV: unique headers including case-sensitive `username`; extra columns allowed.
136
+ Ragged records and blank usernames fail.
137
+ - TXT: one username per line; blank lines ignored.
138
+
139
+ Files use UTF-8 with optional BOM. See examples/export_shape.json (synthetic).
140
+ These are documented schemas, NOT a guarantee of compatibility with all/current
141
+ Instagram exports. HTML, ZIP and automatic discovery/merging of split export
142
+ files are unsupported. Test real authorized samples privately before claiming
143
+ support for their format.
144
+
145
+ ## Use cases and limitations
146
+
147
+ Analyze local account lists, compare dated snapshots, or teach set operations
148
+ with fictional social data. `not_following_back = following - followers`,
149
+ `fans = followers - following`, and `mutuals = intersection`.
150
+
151
+ A removed username only means absence in the later dataset, NOT proof of an
152
+ unfollow. Renames, account changes, timing and incomplete inputs matter. Compare
153
+ same-kind lists from the same account. No automatic repair, live account
154
+ verification, access-control bypass or encrypted storage is provided. Memory
155
+ grows with input size. Typical set operations are linear under ordinary hashing
156
+ assumptions; sorting output adds O(k log k).
157
+
158
+ ## Validation, teamwork and release
159
+
160
+ See TEST_RESULTS.txt for executed checks and untested parts. Real Instagram
161
+ login/collection was NOT tested here. A manual GitHub Actions workflow publishes to PyPI via Trusted Publishing.
162
+ See CONTRIBUTING.md, docs/DEMO.md and docs/QA.md.
163
+ Follow course AI disclosure rules and report actual team contributions honestly.
164
+
165
+ ## License
166
+
167
+ MIT for this supplied implementation; confirm ownership/permissions for any
168
+ existing material retained when integrating into a team repository.
@@ -0,0 +1,28 @@
1
+ CONTRIBUTING.md
2
+ LICENSE
3
+ MANIFEST.in
4
+ README.md
5
+ TEST_RESULTS.txt
6
+ main.py
7
+ pyproject.toml
8
+ docs/DEMO.md
9
+ docs/QA.md
10
+ examples/demo.py
11
+ examples/export_shape.json
12
+ examples/followers.csv
13
+ examples/followers.json
14
+ examples/followers.txt
15
+ examples/followers_after.json
16
+ examples/following.json
17
+ src/InstagramFollowerAnalysis.egg-info/PKG-INFO
18
+ src/InstagramFollowerAnalysis.egg-info/SOURCES.txt
19
+ src/InstagramFollowerAnalysis.egg-info/dependency_links.txt
20
+ src/InstagramFollowerAnalysis.egg-info/entry_points.txt
21
+ src/InstagramFollowerAnalysis.egg-info/requires.txt
22
+ src/InstagramFollowerAnalysis.egg-info/top_level.txt
23
+ src/igfollowchecker/__init__.py
24
+ src/igfollowchecker/__main__.py
25
+ src/igfollowchecker/cli.py
26
+ src/igfollowchecker/core.py
27
+ src/igfollowchecker/live.py
28
+ tests/test_package.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ igfollowchecker = igfollowchecker.cli:main
@@ -0,0 +1,4 @@
1
+ """Local analysis and optional live collection; imports have no browser side effects."""
2
+ from .core import analyze, compare_snapshots, load_users, normalize_username
3
+ __version__ = "0.2.0"
4
+ __all__ = ["analyze", "compare_snapshots", "load_users", "normalize_username"]
@@ -0,0 +1,2 @@
1
+ from .cli import main
2
+ raise SystemExit(main())
@@ -0,0 +1,65 @@
1
+ import argparse
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+ from . import __version__
6
+ from .core import analyze, compare_snapshots, load_users
7
+ from .live import CollectionError
8
+
9
+ def main(argv=None):
10
+ parser = argparse.ArgumentParser(description="Local follower analysis and optional live collection")
11
+ parser.add_argument("--version", action="version", version=__version__)
12
+ sub = parser.add_subparsers(dest="command", required=True)
13
+ a = sub.add_parser("analyze")
14
+ a.add_argument("--followers", required=True)
15
+ a.add_argument("--following", required=True)
16
+ d = sub.add_parser("diff")
17
+ d.add_argument("--before", required=True)
18
+ d.add_argument("--after", required=True)
19
+ for p in (a, d):
20
+ p.add_argument("--json", action="store_true")
21
+ p.add_argument("--output")
22
+ c = sub.add_parser("collect", help="Visible Chrome, manual login/list selection")
23
+ c.add_argument("--username", required=True)
24
+ c.add_argument("--output-dir", required=True)
25
+ c.add_argument("--max-scrolls", type=int, default=200)
26
+ c.add_argument("--pause", type=float, default=1.5)
27
+ c.add_argument("--expected-followers", type=int)
28
+ c.add_argument("--expected-following", type=int)
29
+ args = parser.parse_args(argv)
30
+ try:
31
+ if args.command == "collect":
32
+ from .live import collect_live
33
+ result = collect_live(args.username, args.output_dir, max_scrolls=args.max_scrolls,
34
+ pause=args.pause, expected_followers=args.expected_followers,
35
+ expected_following=args.expected_following)
36
+ print(json.dumps(result, indent=2))
37
+ print("Review private files and metadata before analysis. Completeness is unverified.")
38
+ return 0
39
+ result = (analyze(load_users(args.followers), load_users(args.following)) if args.command == "analyze"
40
+ else compare_snapshots(load_users(args.before), load_users(args.after)))
41
+ encoded = json.dumps(result, ensure_ascii=False, indent=2)
42
+ if args.output:
43
+ with Path(args.output).open("x", encoding="utf-8") as stream:
44
+ stream.write(encoded + "\n")
45
+ if args.json:
46
+ print(encoded)
47
+ else:
48
+ for key, value in result.items():
49
+ if isinstance(value, dict):
50
+ print("Counts: " + ", ".join(f"{k}={v}" for k, v in value.items()))
51
+ elif isinstance(value, list):
52
+ print(f"{key} ({len(value)}): " + (", ".join(value) or "(none)"))
53
+ else:
54
+ print(f"{key}: {value}")
55
+ return 0
56
+ except KeyboardInterrupt:
57
+ print("Cancelled. Inspect output for partial files if saving was interrupted.", file=sys.stderr)
58
+ return 130
59
+ except (OSError, ValueError, UnicodeError, CollectionError) as exc:
60
+ print(f"igfollowchecker: {exc}", file=sys.stderr)
61
+ return 2
62
+
63
+
64
+ if __name__ == "__main__":
65
+ raise SystemExit(main())
@@ -0,0 +1,76 @@
1
+ import csv
2
+ import json
3
+ import re
4
+ from pathlib import Path
5
+ _PATTERN = re.compile(r"[a-z0-9._]{1,30}\Z", re.ASCII)
6
+
7
+ def normalize_username(value):
8
+ if not isinstance(value, str):
9
+ raise ValueError("Username must be a string")
10
+ value = value.strip().removeprefix("@").lower()
11
+ if not _PATTERN.fullmatch(value):
12
+ raise ValueError("Invalid username syntax")
13
+ return value
14
+
15
+ def _users(values):
16
+ if isinstance(values, (str, bytes, dict)):
17
+ raise ValueError("Expected an iterable of username strings")
18
+ try:
19
+ return {normalize_username(value) for value in values}
20
+ except TypeError as exc:
21
+ raise ValueError("Expected an iterable of username strings") from exc
22
+
23
+ def _json_values(data):
24
+ if isinstance(data, dict):
25
+ keys = [k for k in ("usernames", "relationships_following", "relationships_followers") if k in data]
26
+ if len(keys) != 1:
27
+ raise ValueError("JSON object must have exactly one supported list key")
28
+ data = data[keys[0]]
29
+ if not isinstance(data, list):
30
+ raise ValueError("Expected a JSON list")
31
+ if all(isinstance(item, str) for item in data):
32
+ return data
33
+ result = []
34
+ for item in data:
35
+ if not isinstance(item, dict) or not isinstance(item.get("string_list_data"), list) or not item["string_list_data"]:
36
+ raise ValueError("Expected non-empty string_list_data objects; mixed formats are not supported")
37
+ for record in item["string_list_data"]:
38
+ if not isinstance(record, dict) or not isinstance(record.get("value"), str):
39
+ raise ValueError("Expected a string value in string_list_data")
40
+ result.append(record["value"])
41
+ return result
42
+
43
+ def load_users(path):
44
+ path = Path(path)
45
+ with path.open(encoding="utf-8-sig", newline="") as stream:
46
+ if path.suffix.lower() == ".json":
47
+ values = _json_values(json.load(stream))
48
+ elif path.suffix.lower() == ".txt":
49
+ values = [line.strip() for line in stream if line.strip()]
50
+ elif path.suffix.lower() == ".csv":
51
+ try:
52
+ reader = csv.reader(stream, strict=True)
53
+ header = next(reader, None)
54
+ if not header or header.count("username") != 1 or len(set(header)) != len(header):
55
+ raise ValueError("CSV requires unique headers including 'username'")
56
+ column, values = header.index("username"), []
57
+ for row in reader:
58
+ if len(row) != len(header):
59
+ raise ValueError(f"Wrong cell count near CSV line {reader.line_num}")
60
+ values.append(row[column])
61
+ except csv.Error as exc:
62
+ raise ValueError("Malformed CSV") from exc
63
+ else:
64
+ raise ValueError("Supported extensions: .json, .csv, .txt")
65
+ return _users(values)
66
+
67
+ def analyze(followers, following):
68
+ followers, following = _users(followers), _users(following)
69
+ return {"counts": {"followers": len(followers), "following": len(following), "mutuals": len(followers & following)},
70
+ "not_following_back": sorted(following - followers),
71
+ "fans": sorted(followers - following), "mutuals": sorted(followers & following)}
72
+
73
+
74
+ def compare_snapshots(before, after):
75
+ before, after = _users(before), _users(after)
76
+ return {"added": sorted(after - before), "removed": sorted(before - after), "unchanged_count": len(before & after)}
@@ -0,0 +1,126 @@
1
+ import json
2
+ import time
3
+ from pathlib import Path
4
+ from datetime import datetime, timezone
5
+ from urllib.parse import urlparse
6
+ from .core import normalize_username
7
+
8
+ class CollectionError(RuntimeError):
9
+ pass
10
+
11
+ _RESERVED = {"accounts", "explore", "reels", "reel", "p", "direct", "stories", "about", "legal", "privacy", "terms", "developer", "challenge"}
12
+
13
+
14
+ def username_from_href(href):
15
+ if not isinstance(href, str):
16
+ return None
17
+ try:
18
+ parsed = urlparse(href)
19
+ if parsed.scheme != "https" or parsed.hostname not in {"instagram.com", "www.instagram.com"} or parsed.username or parsed.password:
20
+ return None
21
+ parts = parsed.path.strip("/").split("/")
22
+ if len(parts) != 1 or parts[0].lower() in _RESERVED:
23
+ return None
24
+ return normalize_username(parts[0]) if not parts[0].startswith("@") else None
25
+ except ValueError:
26
+ return None
27
+
28
+
29
+ def _dialog(driver):
30
+ elements = [e for e in driver.find_elements("css selector", '[role="dialog"]') if e.is_displayed()]
31
+ return elements[-1] if elements else False
32
+
33
+
34
+ _SCROLL = """
35
+ const d=arguments[0];
36
+ const nodes=[d,...d.querySelectorAll('*')].filter(e => e.clientHeight>0 &&
37
+ e.scrollHeight>e.clientHeight+2 && ['auto','scroll'].includes(getComputedStyle(e).overflowY));
38
+ if (!nodes.length) return null;
39
+ nodes.sort((a,b)=>b.clientHeight-a.clientHeight);
40
+ const e=nodes[0]; e.scrollTop+=Math.max(1,e.clientHeight*0.65);
41
+ return {top:e.scrollTop,height:e.scrollHeight};
42
+ """
43
+
44
+
45
+ def _read_dialog(driver, wait, *, max_scrolls, pause):
46
+ names, stable, previous, reason = set(), 0, None, "scroll_limit"
47
+ def harvest(dialog):
48
+ for anchor in dialog.find_elements("css selector", 'a[href]'):
49
+ name = username_from_href(anchor.get_attribute("href"))
50
+ if name:
51
+ names.add(name)
52
+ for _ in range(max_scrolls):
53
+ dialog = wait.until(_dialog)
54
+ harvest(dialog)
55
+ state = driver.execute_script(_SCROLL, dialog)
56
+ signature = (len(names), None) if state is None else (len(names), state["top"], state["height"])
57
+ stable = stable + 1 if signature == previous else 0
58
+ previous = signature
59
+ if stable >= 5:
60
+ reason = "no_observed_progress"
61
+ break
62
+ time.sleep(pause)
63
+ harvest(wait.until(_dialog))
64
+ if not names:
65
+ raise CollectionError("No profiles collected: empty list, wrong dialog, page changes or loading failure. Nothing saved.")
66
+ return sorted(names), reason
67
+
68
+
69
+ def collect_live(username, output_dir, *, max_scrolls=200, pause=1.5,
70
+ expected_followers=None, expected_following=None, prompt=input):
71
+ username = normalize_username(username)
72
+ if not 1 <= max_scrolls <= 2000 or not 1.5 <= pause <= 60:
73
+ raise ValueError("max_scrolls must be 1..2000 and pause must be 1.5..60 seconds")
74
+ if any(c is not None and c < 0 for c in (expected_followers, expected_following)):
75
+ raise ValueError("Expected counts cannot be negative")
76
+ output = Path(output_dir)
77
+ if output.exists():
78
+ raise ValueError("Choose a NEW output directory")
79
+ try:
80
+ from selenium import webdriver
81
+ from selenium.webdriver.support.ui import WebDriverWait
82
+ from selenium.common.exceptions import WebDriverException
83
+ except ImportError as exc:
84
+ raise CollectionError('Install the live extra: python -m pip install -e ".[live]"') from exc
85
+ driver = None
86
+ try:
87
+ driver = webdriver.Chrome()
88
+ driver.set_page_load_timeout(45)
89
+ wait = WebDriverWait(driver, 20)
90
+ driver.get("https://www.instagram.com/")
91
+ prompt("Log in yourself in Chrome and complete verification manually. Press Enter here when ready; Ctrl+C cancels: ")
92
+ lists, details = {}, {}
93
+ for kind, expected in (("followers", expected_followers), ("following", expected_following)):
94
+ driver.get(f"https://www.instagram.com/{username}/")
95
+ prompt(f"Open @{username}'s {kind} list in Chrome. Confirm the correct list, then press Enter here: ")
96
+ print(f"Collecting {kind}; do not interact with Chrome during collection.")
97
+ users, reason = _read_dialog(driver, wait, max_scrolls=max_scrolls, pause=pause)
98
+ if expected is not None and len(users) != expected:
99
+ raise CollectionError(f"{kind}: collected {len(users)}, expected {expected}. Nothing saved.")
100
+ lists[kind] = users
101
+ details[kind] = {"collected": len(users), "expected_count": expected,
102
+ "count_matches": None if expected is None else len(users) == expected,
103
+ "stop_reason": reason}
104
+ print(f"Collected {len(users)} {kind}; completeness unverified.")
105
+ if prompt("Confirm correct lists. Type SAVE to store them locally, anything else to cancel: ").strip() != "SAVE":
106
+ raise CollectionError("Cancelled; no data saved")
107
+ output.mkdir(parents=True, exist_ok=False)
108
+ for kind, users in lists.items():
109
+ with (output / f"{kind}.json").open("x", encoding="utf-8") as stream:
110
+ json.dump(users, stream, indent=2)
111
+ metadata = {"schema_version": 1, "username": username,
112
+ "captured_at_utc": datetime.now(timezone.utc).isoformat(),
113
+ "source": "visible_browser_best_effort", "completeness": "unverified",
114
+ "warning": "Counts and scroll stability do not prove completeness; review before analysis.", "lists": details}
115
+ with (output / "metadata.json").open("x", encoding="utf-8") as stream:
116
+ json.dump(metadata, stream, indent=2)
117
+ return metadata
118
+ except WebDriverException as exc:
119
+ raise CollectionError("Browser collection failed. Check Chrome, login, access and correct list selection; no bypass is attempted.") from exc
120
+ finally:
121
+ if driver is not None:
122
+ try:
123
+ driver.quit()
124
+ except Exception:
125
+ pass
126
+
@@ -0,0 +1,121 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ from pathlib import Path
5
+ import tempfile
6
+ import unittest
7
+ from unittest.mock import patch
8
+ from igfollowchecker import analyze, compare_snapshots, load_users, normalize_username
9
+ from igfollowchecker.cli import main
10
+ from igfollowchecker.live import CollectionError, _read_dialog, username_from_href
11
+
12
+
13
+ class Tests(unittest.TestCase):
14
+ def setUp(self):
15
+ self.temp = tempfile.TemporaryDirectory()
16
+ self.addCleanup(self.temp.cleanup)
17
+ self.base = Path(self.temp.name)
18
+
19
+ def file(self, name, text):
20
+ p = self.base / name
21
+ p.write_text(text, encoding="utf-8")
22
+ return p
23
+
24
+ def test_normalize(self):
25
+ self.assertEqual(normalize_username(" @Alice_1 "), "alice_1")
26
+
27
+ def test_invalid_names(self):
28
+ for value in ("", "a b", "@@a", 12, "a"*31):
29
+ with self.subTest(value=value), self.assertRaises(ValueError): normalize_username(value)
30
+
31
+ def test_analysis(self):
32
+ self.assertEqual(analyze(["a", "b"], ["b", "c"]), {"counts": {"followers":2,"following":2,"mutuals":1}, "fans":["a"], "not_following_back":["c"], "mutuals":["b"]})
33
+
34
+ def test_duplicates(self):
35
+ self.assertEqual(analyze(["A", "@a"], [])["counts"]["followers"], 1)
36
+
37
+ def test_empty(self): self.assertEqual(analyze([], [])["fans"], [])
38
+
39
+ def test_no_mutation(self):
40
+ a = {"a"}; analyze(a, []); self.assertEqual(a, {"a"})
41
+
42
+ def test_wrong_iterable(self):
43
+ with self.assertRaises(ValueError): analyze("a", [])
44
+
45
+ def test_diff(self):
46
+ self.assertEqual(compare_snapshots(["a","b"],["b","c"]), {"added":["c"],"removed":["a"],"unchanged_count":1})
47
+
48
+ def test_json(self): self.assertEqual(load_users(self.file("a.json", '["Alice"]')), {"alice"})
49
+
50
+ def test_wrapper(self): self.assertEqual(load_users(self.file("a.json", '{"usernames":["a"]}')), {"a"})
51
+
52
+ def test_export(self):
53
+ text = '{"relationships_following":[{"string_list_data":[{"value":"a"}]}]}'
54
+ self.assertEqual(load_users(self.file("a.json", text)), {"a"})
55
+
56
+ def test_invalid_json(self):
57
+ for text in ('{', '{}', 'null', '[3]', '[{"string_list_data":[]}]', '{"usernames":[],"relationships_following":[]}'):
58
+ with self.subTest(text=text), self.assertRaises(ValueError): load_users(self.file("a.json", text))
59
+
60
+ def test_csv(self): self.assertEqual(load_users(self.file("a.csv", 'username,note\na,"hi, there"\n')), {"a"})
61
+
62
+ def test_bad_csv(self):
63
+ for text in ('name\na\n','username\na,b\n','username,username\na,b\n','username,note\n,x\n'):
64
+ with self.subTest(text=text), self.assertRaises(ValueError): load_users(self.file("a.csv", text))
65
+
66
+ def test_txt_bom(self): self.assertEqual(load_users(self.file("a.txt", '\ufeffAlice\n\n@bob\n')), {"alice","bob"})
67
+
68
+ def test_extension(self):
69
+ with self.assertRaises(ValueError): load_users(self.file("a.html", 'x'))
70
+
71
+ def test_missing(self):
72
+ with self.assertRaises(OSError): load_users(self.base / "none.json")
73
+
74
+ def test_cli_json(self):
75
+ a = self.file("a.txt", "a"); b = self.file("b.txt", "b"); out = io.StringIO()
76
+ with contextlib.redirect_stdout(out): code = main(["analyze","--followers",str(a),"--following",str(b),"--json"])
77
+ self.assertEqual(code,0); self.assertEqual(json.loads(out.getvalue())["fans"],["a"])
78
+
79
+ def test_output_and_no_overwrite(self):
80
+ a = self.file("a.txt","a"); output = self.base / "out.json"
81
+ args = ["diff","--before",str(a),"--after",str(a),"--output",str(output)]
82
+ with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(main(args),0)
83
+ with contextlib.redirect_stderr(io.StringIO()): self.assertEqual(main(args),2)
84
+ self.assertEqual(json.loads(output.read_text())["removed"],[])
85
+
86
+ def test_bad_cli(self):
87
+ with contextlib.redirect_stderr(io.StringIO()): self.assertEqual(main(["diff","--before","missing.json","--after","missing.json"]),2)
88
+
89
+ def test_profile_url(self): self.assertEqual(username_from_href("https://www.instagram.com/Alice/"), "alice")
90
+
91
+ def test_bad_urls(self):
92
+ for value in (None,"", "http://instagram.com/a/", "https://instagram.com.evil.org/a/", "https://instagram.com/explore/", "https://instagram.com/a/followers/", "https://instagram.com/@a/", "https://instagram.com/"):
93
+ with self.subTest(value=value): self.assertIsNone(username_from_href(value))
94
+
95
+ @patch("igfollowchecker.live.time.sleep")
96
+ def test_dialog_stopping(self, sleep):
97
+ class Anchor:
98
+ def get_attribute(self, key): return "https://instagram.com/alice/"
99
+ class Dialog:
100
+ def find_elements(self,*args): return [Anchor()]
101
+ class Wait:
102
+ def until(self,condition): return Dialog()
103
+ class Driver:
104
+ def execute_script(self,*args): return {"top":1,"height":2}
105
+ users, reason = _read_dialog(Driver(),Wait(),max_scrolls=20,pause=1.5)
106
+ self.assertEqual(users,["alice"]); self.assertEqual(reason,"no_observed_progress")
107
+ self.assertLess(sleep.call_count,20)
108
+ self.assertEqual(_read_dialog(Driver(),Wait(),max_scrolls=1,pause=1.5)[1],"scroll_limit")
109
+
110
+ @patch("igfollowchecker.live.time.sleep")
111
+ def test_empty_dialog_error(self, sleep):
112
+ class Dialog:
113
+ def find_elements(self,*args): return []
114
+ class Wait:
115
+ def until(self,condition): return Dialog()
116
+ class Driver:
117
+ def execute_script(self,*args): return None
118
+ with self.assertRaises(CollectionError): _read_dialog(Driver(),Wait(),max_scrolls=1,pause=1.5)
119
+
120
+
121
+ if __name__ == "__main__": unittest.main()