syscred 2.2.0__py3-none-any.whl

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.
@@ -0,0 +1,87 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Test Script for GraphRAG
4
+ ========================
5
+ Verifies that the GraphRAG module can correctly:
6
+ 1. Connect to an in-memory ontology.
7
+ 2. Retrieve context for a domain that has history.
8
+ """
9
+
10
+ import sys
11
+ import os
12
+
13
+ # Add parent directory to path to allow imports
14
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
15
+
16
+ from syscred.ontology_manager import OntologyManager
17
+ from syscred.graph_rag import GraphRAG
18
+
19
+ def test_graphrag_retrieval():
20
+ print("=== Testing GraphRAG Retrieval Logic ===\n")
21
+
22
+ # 1. Setup In-Memory Ontology
23
+ print("[1] Initializing in-memory Ontology...")
24
+ om = OntologyManager(base_ontology_path=None, data_path=None)
25
+
26
+ # 2. Add Fake History (Memory)
27
+ print("[2] Injecting test memory for 'lemonde.fr'...")
28
+ fake_report = {
29
+ 'scoreCredibilite': 0.95,
30
+ 'informationEntree': 'https://www.lemonde.fr/article/test',
31
+ 'resumeAnalyse': "Reliable source.",
32
+ 'reglesAppliquees': {
33
+ 'source_analysis': {'reputation': 'High', 'domain': 'lemonde.fr'}
34
+ }
35
+ }
36
+ # Add it 3 times to simulate history
37
+ om.add_evaluation_triplets(fake_report)
38
+ om.add_evaluation_triplets(fake_report)
39
+ om.add_evaluation_triplets(fake_report)
40
+ print(" -> Added 3 evaluation records.")
41
+
42
+ # 3. Initialize GraphRAG
43
+ rag = GraphRAG(om)
44
+
45
+ # 4. Query Context
46
+ domain = "lemonde.fr"
47
+ print(f"\n[3] Querying GraphRAG for domain: '{domain}'...")
48
+ context = rag.get_context(domain)
49
+
50
+ print("\n--- Result Context (Domain History) ---")
51
+ print(context['full_text'])
52
+ print("---------------------------------------\n")
53
+
54
+ # 5. Validation 1 (History)
55
+ if "Analyzed 3 times" in context['full_text']:
56
+ print("✅ SUCCESS: GraphRAG correctly remembered the history.")
57
+ else:
58
+ print("❌ FAILURE: GraphRAG did not return the expected history count.")
59
+
60
+ # 6. Test Similar Claims (New Feature)
61
+ print(f"\n[4] Testing 'Similar Claims' for keywords: ['lemonde', 'fake']...")
62
+ # The previous injection didn't use 'fake', let's check what it finds or if we need to inject more
63
+ # Our fake_report had content: 'https://www.lemonde.fr/article/test'
64
+ # The new logic searches regex in 'informationContent'
65
+
66
+ # Let's add a specifically claim-like entry
67
+ fake_claim = {
68
+ 'scoreCredibilite': 0.1,
69
+ 'informationEntree': 'The earth is flat and fake',
70
+ 'resumeAnalyse': "False claim.",
71
+ 'reglesAppliquees': {'source_analysis': {'reputation': 'Low'}}
72
+ }
73
+ om.add_evaluation_triplets(fake_claim)
74
+
75
+ # Search for 'flat'
76
+ similar_context = rag.get_context("unknown.com", keywords=["flat", "earth"])
77
+ print("\n--- Result Context (Similar Claims) ---")
78
+ print(similar_context['full_text'])
79
+ print("---------------------------------------\n")
80
+
81
+ if "Found 1 similar claims" in similar_context['full_text'] or "The earth is flat" in similar_context['full_text']:
82
+ print("✅ SUCCESS: GraphRAG found similar claims by keywords.")
83
+ else:
84
+ print("❌ FAILURE: GraphRAG did not find the injected similar claim.")
85
+
86
+ if __name__ == "__main__":
87
+ test_graphrag_retrieval()
syscred/test_phase1.py ADDED
@@ -0,0 +1,28 @@
1
+ import sys
2
+ import os
3
+
4
+ # Add project root to path
5
+ sys.path.insert(0, os.getcwd())
6
+
7
+ from syscred.api_clients import ExternalAPIClients
8
+
9
+ def test_backlinks():
10
+ client = ExternalAPIClients()
11
+
12
+ test_urls = [
13
+ "https://www.lemonde.fr", # High + Old
14
+ "https://www.infowars.com", # Low + Old
15
+ "https://example.com", # Unknown + Old
16
+ "https://new-suspicious-site.xyz" # Unknown + New (likely)
17
+ ]
18
+
19
+ print("=== Testing Backlink Estimation Heuristic ===")
20
+ for url in test_urls:
21
+ print(f"\nTesting: {url}")
22
+ res = client.estimate_backlinks(url)
23
+ print(f" Count: {res['estimated_count']}")
24
+ print(f" Method: {res['method']}")
25
+ print(f" Note: {res['note']}")
26
+
27
+ if __name__ == "__main__":
28
+ test_backlinks()
syscred/test_phase2.py ADDED
@@ -0,0 +1,55 @@
1
+ import sys
2
+ import os
3
+
4
+ # Add project root to path
5
+ sys.path.insert(0, os.path.dirname(os.getcwd())) # Assumes running from syscred/
6
+
7
+ try:
8
+ from syscred.verification_system import CredibilityVerificationSystem
9
+ except ImportError:
10
+ # Just in case of path issues
11
+ sys.path.append(os.getcwd())
12
+ from verification_system import CredibilityVerificationSystem
13
+
14
+ def test_nlp_fallbacks():
15
+ print("=== Testing NLP Hybrid Fallbacks ===")
16
+
17
+ # Initialize without loading standard ML (to test our new hybrid logic)
18
+ # Note: verification_system uses HAS_ML flag, but we want to test specific methods
19
+ syscred = CredibilityVerificationSystem(load_ml_models=False)
20
+
21
+ # Test 1: Coherence
22
+ print("\n[Test 1] Coherence")
23
+ coherent_text = "The quick brown fox jumps over the lazy dog. The dog was not amused. It barked loudly."
24
+ incoherent_text = "The quick brown fox. Banana republic creates clouds. Jump over the moon."
25
+
26
+ score1 = syscred._calculate_coherence(coherent_text)
27
+ score2 = syscred._calculate_coherence(incoherent_text)
28
+
29
+ print(f" Coherent Text Score: {score1}")
30
+ print(f" Incoherent Text Score: {score2}")
31
+
32
+ if score1 > score2:
33
+ print(" ✓ Coherence logic working (Metric discriminates)")
34
+ else:
35
+ print(" ! Coherence scores inconclusive (Might be heuristic limitations)")
36
+
37
+ # Test 2: Bias
38
+ print("\n[Test 2] Bias")
39
+ neutral_text = "The government announced a new policy today regarding taxation."
40
+ biased_text = "The corrupt regime stands accused of treason against the people by radical idiots."
41
+
42
+ res1 = syscred._analyze_bias(neutral_text)
43
+ res2 = syscred._analyze_bias(biased_text)
44
+
45
+ print(f" Neutral: {res1['label']} (Score: {res1['score']:.2f})")
46
+ print(f" Biased: {res2['label']} (Score: {res2['score']:.2f})")
47
+ print(f" Method Used: {res1.get('method', 'Unknown')}")
48
+
49
+ if res2['score'] > res1['score']:
50
+ print(" ✓ Bias detection working")
51
+ else:
52
+ print(" ! Bias detection inconclusive")
53
+
54
+ if __name__ == "__main__":
55
+ test_nlp_fallbacks()
syscred/test_suite.py ADDED
@@ -0,0 +1,64 @@
1
+ import unittest
2
+ import sys
3
+ import os
4
+
5
+ # Point to parent directory (MonCode) so we can import 'syscred' package
6
+ # Current file is in MonCode/syscred/test_suite.py
7
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8
+
9
+ from syscred.verification_system import CredibilityVerificationSystem
10
+ from syscred.api_clients import ExternalAPIClients
11
+
12
+ class TestSysCRED(unittest.TestCase):
13
+
14
+ @classmethod
15
+ def setUpClass(cls):
16
+ print("\n[TestSysCRED] Setting up system...")
17
+ cls.system = CredibilityVerificationSystem(load_ml_models=False)
18
+ cls.client = cls.system.api_clients
19
+
20
+ def test_backlink_estimation_heuristic(self):
21
+ """Test that backlink estimation respects reputation."""
22
+ lemonde = self.client.estimate_backlinks("https://www.lemonde.fr")
23
+ infowars = self.client.estimate_backlinks("https://infowars.com")
24
+
25
+ self.assertGreater(lemonde['estimated_count'], infowars['estimated_count'],
26
+ "High reputation should have more backlinks than Low")
27
+ self.assertEqual(lemonde['method'], 'heuristic_v2.1')
28
+
29
+ def test_coherence_heuristic(self):
30
+ """Test coherence scoring heuristic."""
31
+ good_text = "This is a coherent sentence. It follows logically."
32
+ bad_text = "This is. Random words. Banana. Cloud."
33
+
34
+ score_good = self.system._calculate_coherence(good_text)
35
+ score_bad = self.system._calculate_coherence(bad_text)
36
+
37
+ self.assertTrue(0 <= score_good <= 1)
38
+ # Note: Heuristic using sentence length variance might be sensitive
39
+ # bad_text has very short sentences, so average length is small -> penalty
40
+ # good_text has normal length
41
+ self.assertGreaterEqual(score_good, score_bad, "Coherent text should score >= incoherent")
42
+
43
+ def test_bias_heuristic(self):
44
+ """Test bias detection heuristic."""
45
+ neutral = "The economy grew by 2%."
46
+ biased = "The radical corrupt regime is destroying us!"
47
+
48
+ res_neutral = self.system._analyze_bias(neutral)
49
+ res_biased = self.system._analyze_bias(biased)
50
+
51
+ self.assertLess(res_neutral['score'], res_biased['score'])
52
+ self.assertIn("biased", res_biased['label'].lower())
53
+
54
+ def test_full_pipeline(self):
55
+ """Test the full verification pipeline (integration test)."""
56
+ input_data = "https://www.example.com"
57
+ result = self.system.verify_information(input_data)
58
+
59
+ self.assertIn('scoreCredibilite', result)
60
+ self.assertIn('resumeAnalyse', result)
61
+ self.assertIsNotNone(result['scoreCredibilite'])
62
+
63
+ if __name__ == '__main__':
64
+ unittest.main()