@geoly-ai/social-hub-cli 0.3.46 → 0.3.48

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.
@@ -1,152 +1,152 @@
1
- import os
2
- from firecrawl import FirecrawlApp
3
- import json
4
- from dotenv import load_dotenv
5
- from openai import OpenAI
6
-
7
- # ANSI color codes
8
- class Colors:
9
- CYAN = '\033[96m'
10
- YELLOW = '\033[93m'
11
- GREEN = '\033[92m'
12
- RED = '\033[91m'
13
- MAGENTA = '\033[95m'
14
- BLUE = '\033[94m'
15
- RESET = '\033[0m'
16
-
17
- # Load environment variables
18
- load_dotenv()
19
-
20
- # Retrieve API keys from environment variables
21
- firecrawl_api_key = os.getenv("FIRECRAWL_API_KEY")
22
- openai_api_key = os.getenv("OPENAI_API_KEY")
23
-
24
- # Initialize the FirecrawlApp and OpenAI client
25
- app = FirecrawlApp(api_key=firecrawl_api_key)
26
- client = OpenAI(api_key=openai_api_key)
27
-
28
- # Find the page that most likely contains the objective
29
- def find_relevant_page_via_map(objective, url, app, client):
30
- try:
31
- print(f"{Colors.CYAN}Understood. The objective is: {objective}{Colors.RESET}")
32
- print(f"{Colors.CYAN}Initiating search on the website: {url}{Colors.RESET}")
33
-
34
- map_prompt = f"""
35
- The map function generates a list of URLs from a website and it accepts a search parameter. Based on the objective of: {objective}, come up with a 1-2 word search parameter that will help us find the information we need. Only respond with 1-2 words nothing else.
36
- """
37
-
38
- print(f"{Colors.YELLOW}Analyzing objective to determine optimal search parameter...{Colors.RESET}")
39
- completion = client.chat.completions.create(
40
- model="o1-preview",
41
- messages=[
42
- {
43
- "role": "user",
44
- "content": [
45
- {
46
- "type": "text",
47
- "text": map_prompt
48
- }
49
- ]
50
- }
51
- ]
52
- )
53
-
54
- map_search_parameter = completion.choices[0].message.content
55
- print(f"{Colors.GREEN}Optimal search parameter identified: {map_search_parameter}{Colors.RESET}")
56
-
57
- print(f"{Colors.YELLOW}Mapping website using the identified search parameter...{Colors.RESET}")
58
- map_website = app.map_url(url, params={"search": map_search_parameter})
59
- print(f"{Colors.GREEN}Website mapping completed successfully.{Colors.RESET}")
60
- print(f"{Colors.GREEN}Located {len(map_website)} relevant links.{Colors.RESET}")
61
- return map_website
62
- except Exception as e:
63
- print(f"{Colors.RED}Error encountered during relevant page identification: {str(e)}{Colors.RESET}")
64
- return None
65
-
66
- # Scrape the top 3 pages and see if the objective is met, if so return in json format else return None
67
- def find_objective_in_top_pages(map_website, objective, app, client):
68
- try:
69
- # Get top 3 links from the map result
70
- top_links = map_website[:3] if isinstance(map_website, list) else []
71
- print(f"{Colors.CYAN}Proceeding to analyze top {len(top_links)} links: {top_links}{Colors.RESET}")
72
-
73
- for link in top_links:
74
- print(f"{Colors.YELLOW}Initiating scrape of page: {link}{Colors.RESET}")
75
- # Scrape the page
76
- scrape_result = app.scrape_url(link, params={'formats': ['markdown']})
77
- print(f"{Colors.GREEN}Page scraping completed successfully.{Colors.RESET}")
78
-
79
-
80
- # Check if objective is met
81
- check_prompt = f"""
82
- Given the following scraped content and objective, determine if the objective is met.
83
- If it is, extract the relevant information in a simple and concise JSON format. Use only the necessary fields and avoid nested structures if possible.
84
- If the objective is not met with confidence, respond with 'Objective not met'.
85
-
86
- Objective: {objective}
87
- Scraped content: {scrape_result['markdown']}
88
-
89
- Remember:
90
- 1. Only return JSON if you are confident the objective is fully met.
91
- 2. Keep the JSON structure as simple and flat as possible.
92
- 3. Do not include any explanations or markdown formatting in your response.
93
- """
94
-
95
- completion = client.chat.completions.create(
96
- model="o1-preview",
97
- messages=[
98
- {
99
- "role": "user",
100
- "content": [
101
- {
102
- "type": "text",
103
- "text": check_prompt
104
- }
105
- ]
106
- }
107
- ]
108
- )
109
-
110
- result = completion.choices[0].message.content
111
-
112
- if result != "Objective not met":
113
- print(f"{Colors.GREEN}Objective potentially fulfilled. Relevant information identified.{Colors.RESET}")
114
- try:
115
- return json.loads(result)
116
- except json.JSONDecodeError:
117
- print(f"{Colors.RED}Error in parsing response. Proceeding to next page...{Colors.RESET}")
118
- else:
119
- print(f"{Colors.YELLOW}Objective not met on this page. Proceeding to next link...{Colors.RESET}")
120
-
121
- print(f"{Colors.RED}All available pages analyzed. Objective not fulfilled in examined content.{Colors.RESET}")
122
- return None
123
-
124
- except Exception as e:
125
- print(f"{Colors.RED}Error encountered during page analysis: {str(e)}{Colors.RESET}")
126
- return None
127
-
128
- # Main function to execute the process
129
- def main():
130
- # Get user input
131
- url = input(f"{Colors.BLUE}Enter the website to crawl: {Colors.RESET}")
132
- objective = input(f"{Colors.BLUE}Enter your objective: {Colors.RESET}")
133
-
134
- print(f"{Colors.YELLOW}Initiating web crawling process...{Colors.RESET}")
135
- # Find the relevant page
136
- map_website = find_relevant_page_via_map(objective, url, app, client)
137
-
138
- if map_website:
139
- print(f"{Colors.GREEN}Relevant pages identified. Proceeding with detailed analysis...{Colors.RESET}")
140
- # Find objective in top pages
141
- result = find_objective_in_top_pages(map_website, objective, app, client)
142
-
143
- if result:
144
- print(f"{Colors.GREEN}Objective successfully fulfilled. Extracted information:{Colors.RESET}")
145
- print(f"{Colors.MAGENTA}{json.dumps(result, indent=2)}{Colors.RESET}")
146
- else:
147
- print(f"{Colors.RED}Unable to fulfill the objective with the available content.{Colors.RESET}")
148
- else:
149
- print(f"{Colors.RED}No relevant pages identified. Consider refining the search parameters or trying a different website.{Colors.RESET}")
150
-
151
- if __name__ == "__main__":
152
- main()
1
+ import os
2
+ from firecrawl import FirecrawlApp
3
+ import json
4
+ from dotenv import load_dotenv
5
+ from openai import OpenAI
6
+
7
+ # ANSI color codes
8
+ class Colors:
9
+ CYAN = '\033[96m'
10
+ YELLOW = '\033[93m'
11
+ GREEN = '\033[92m'
12
+ RED = '\033[91m'
13
+ MAGENTA = '\033[95m'
14
+ BLUE = '\033[94m'
15
+ RESET = '\033[0m'
16
+
17
+ # Load environment variables
18
+ load_dotenv()
19
+
20
+ # Retrieve API keys from environment variables
21
+ firecrawl_api_key = os.getenv("FIRECRAWL_API_KEY")
22
+ openai_api_key = os.getenv("OPENAI_API_KEY")
23
+
24
+ # Initialize the FirecrawlApp and OpenAI client
25
+ app = FirecrawlApp(api_key=firecrawl_api_key)
26
+ client = OpenAI(api_key=openai_api_key)
27
+
28
+ # Find the page that most likely contains the objective
29
+ def find_relevant_page_via_map(objective, url, app, client):
30
+ try:
31
+ print(f"{Colors.CYAN}Understood. The objective is: {objective}{Colors.RESET}")
32
+ print(f"{Colors.CYAN}Initiating search on the website: {url}{Colors.RESET}")
33
+
34
+ map_prompt = f"""
35
+ The map function generates a list of URLs from a website and it accepts a search parameter. Based on the objective of: {objective}, come up with a 1-2 word search parameter that will help us find the information we need. Only respond with 1-2 words nothing else.
36
+ """
37
+
38
+ print(f"{Colors.YELLOW}Analyzing objective to determine optimal search parameter...{Colors.RESET}")
39
+ completion = client.chat.completions.create(
40
+ model="o1-preview",
41
+ messages=[
42
+ {
43
+ "role": "user",
44
+ "content": [
45
+ {
46
+ "type": "text",
47
+ "text": map_prompt
48
+ }
49
+ ]
50
+ }
51
+ ]
52
+ )
53
+
54
+ map_search_parameter = completion.choices[0].message.content
55
+ print(f"{Colors.GREEN}Optimal search parameter identified: {map_search_parameter}{Colors.RESET}")
56
+
57
+ print(f"{Colors.YELLOW}Mapping website using the identified search parameter...{Colors.RESET}")
58
+ map_website = app.map_url(url, params={"search": map_search_parameter})
59
+ print(f"{Colors.GREEN}Website mapping completed successfully.{Colors.RESET}")
60
+ print(f"{Colors.GREEN}Located {len(map_website)} relevant links.{Colors.RESET}")
61
+ return map_website
62
+ except Exception as e:
63
+ print(f"{Colors.RED}Error encountered during relevant page identification: {str(e)}{Colors.RESET}")
64
+ return None
65
+
66
+ # Scrape the top 3 pages and see if the objective is met, if so return in json format else return None
67
+ def find_objective_in_top_pages(map_website, objective, app, client):
68
+ try:
69
+ # Get top 3 links from the map result
70
+ top_links = map_website[:3] if isinstance(map_website, list) else []
71
+ print(f"{Colors.CYAN}Proceeding to analyze top {len(top_links)} links: {top_links}{Colors.RESET}")
72
+
73
+ for link in top_links:
74
+ print(f"{Colors.YELLOW}Initiating scrape of page: {link}{Colors.RESET}")
75
+ # Scrape the page
76
+ scrape_result = app.scrape_url(link, params={'formats': ['markdown']})
77
+ print(f"{Colors.GREEN}Page scraping completed successfully.{Colors.RESET}")
78
+
79
+
80
+ # Check if objective is met
81
+ check_prompt = f"""
82
+ Given the following scraped content and objective, determine if the objective is met.
83
+ If it is, extract the relevant information in a simple and concise JSON format. Use only the necessary fields and avoid nested structures if possible.
84
+ If the objective is not met with confidence, respond with 'Objective not met'.
85
+
86
+ Objective: {objective}
87
+ Scraped content: {scrape_result['markdown']}
88
+
89
+ Remember:
90
+ 1. Only return JSON if you are confident the objective is fully met.
91
+ 2. Keep the JSON structure as simple and flat as possible.
92
+ 3. Do not include any explanations or markdown formatting in your response.
93
+ """
94
+
95
+ completion = client.chat.completions.create(
96
+ model="o1-preview",
97
+ messages=[
98
+ {
99
+ "role": "user",
100
+ "content": [
101
+ {
102
+ "type": "text",
103
+ "text": check_prompt
104
+ }
105
+ ]
106
+ }
107
+ ]
108
+ )
109
+
110
+ result = completion.choices[0].message.content
111
+
112
+ if result != "Objective not met":
113
+ print(f"{Colors.GREEN}Objective potentially fulfilled. Relevant information identified.{Colors.RESET}")
114
+ try:
115
+ return json.loads(result)
116
+ except json.JSONDecodeError:
117
+ print(f"{Colors.RED}Error in parsing response. Proceeding to next page...{Colors.RESET}")
118
+ else:
119
+ print(f"{Colors.YELLOW}Objective not met on this page. Proceeding to next link...{Colors.RESET}")
120
+
121
+ print(f"{Colors.RED}All available pages analyzed. Objective not fulfilled in examined content.{Colors.RESET}")
122
+ return None
123
+
124
+ except Exception as e:
125
+ print(f"{Colors.RED}Error encountered during page analysis: {str(e)}{Colors.RESET}")
126
+ return None
127
+
128
+ # Main function to execute the process
129
+ def main():
130
+ # Get user input
131
+ url = input(f"{Colors.BLUE}Enter the website to crawl: {Colors.RESET}")
132
+ objective = input(f"{Colors.BLUE}Enter your objective: {Colors.RESET}")
133
+
134
+ print(f"{Colors.YELLOW}Initiating web crawling process...{Colors.RESET}")
135
+ # Find the relevant page
136
+ map_website = find_relevant_page_via_map(objective, url, app, client)
137
+
138
+ if map_website:
139
+ print(f"{Colors.GREEN}Relevant pages identified. Proceeding with detailed analysis...{Colors.RESET}")
140
+ # Find objective in top pages
141
+ result = find_objective_in_top_pages(map_website, objective, app, client)
142
+
143
+ if result:
144
+ print(f"{Colors.GREEN}Objective successfully fulfilled. Extracted information:{Colors.RESET}")
145
+ print(f"{Colors.MAGENTA}{json.dumps(result, indent=2)}{Colors.RESET}")
146
+ else:
147
+ print(f"{Colors.RED}Unable to fulfill the objective with the available content.{Colors.RESET}")
148
+ else:
149
+ print(f"{Colors.RED}No relevant pages identified. Consider refining the search parameters or trying a different website.{Colors.RESET}")
150
+
151
+ if __name__ == "__main__":
152
+ main()
@@ -25,9 +25,9 @@ class LinksFallbackTests(unittest.TestCase):
25
25
  code = voc.main()
26
26
  return code, json.loads(stdout.getvalue())
27
27
 
28
- def test_arctic_miss_uses_rendered_page_without_loading_browser_cookies(self) -> None:
28
+ def test_arctic_miss_uses_rendered_page_without_direct_network_calls(self) -> None:
29
29
  with (
30
- mock.patch.object(voc.CookieStore, "get", side_effect=AssertionError("browser cookies loaded")) as cookies,
30
+ mock.patch.object(voc.urllib.request, "urlopen", side_effect=AssertionError("direct network call")) as urlopen,
31
31
  mock.patch.object(voc, "arctic_post_by_permalink", return_value=None) as archive,
32
32
  mock.patch.object(voc, "fetch_page_scrape", return_value={"markdown": "Public page"}) as page,
33
33
  mock.patch.object(voc, "collect_subreddit_metrics", return_value=[]),
@@ -42,11 +42,11 @@ class LinksFallbackTests(unittest.TestCase):
42
42
  self.assertEqual(out["errors"], [])
43
43
  archive.assert_called_once()
44
44
  self.assertEqual(page.call_args.kwargs["provider"], "social-hub")
45
- cookies.assert_not_called()
45
+ urlopen.assert_not_called()
46
46
 
47
47
  def test_arctic_miss_without_fallback_reports_archive_not_json(self) -> None:
48
48
  with (
49
- mock.patch.object(voc.CookieStore, "get", side_effect=AssertionError("browser cookies loaded")) as cookies,
49
+ mock.patch.object(voc.urllib.request, "urlopen", side_effect=AssertionError("direct network call")) as urlopen,
50
50
  mock.patch.object(voc, "arctic_post_by_permalink", side_effect=RuntimeError("archive unavailable")),
51
51
  mock.patch.object(voc, "collect_subreddit_metrics", return_value=[]),
52
52
  mock.patch.object(voc, "hub_writeback_items", return_value={"status": "not_applicable"}),
@@ -58,7 +58,7 @@ class LinksFallbackTests(unittest.TestCase):
58
58
  self.assertFalse(out["ok"])
59
59
  self.assertTrue(any("archive unavailable" in error for error in out["errors"]))
60
60
  self.assertTrue(any("Arctic lookup failed" in note for note in out["notes"]))
61
- cookies.assert_not_called()
61
+ urlopen.assert_not_called()
62
62
 
63
63
  def test_auto_fallback_tries_firecrawl_after_social_hub_failure(self) -> None:
64
64
  def page_result(_url: str, *, provider: str, **_kwargs: object) -> dict:
@@ -67,7 +67,7 @@ class LinksFallbackTests(unittest.TestCase):
67
67
  return {"markdown": "Public page"}
68
68
 
69
69
  with (
70
- mock.patch.object(voc.CookieStore, "get", side_effect=AssertionError("browser cookies loaded")) as cookies,
70
+ mock.patch.object(voc.urllib.request, "urlopen", side_effect=AssertionError("direct network call")) as urlopen,
71
71
  mock.patch.object(voc, "arctic_post_by_permalink", return_value=None),
72
72
  mock.patch.object(voc, "fetch_page_scrape", side_effect=page_result) as page,
73
73
  mock.patch.object(voc, "social_hub_unavailable_hint", return_value="Hub unavailable"),
@@ -80,7 +80,7 @@ class LinksFallbackTests(unittest.TestCase):
80
80
  self.assertEqual(code, 0)
81
81
  self.assertEqual(out["items"][0]["page_provider"], "firecrawl")
82
82
  self.assertEqual([call.kwargs["provider"] for call in page.call_args_list], ["social-hub", "firecrawl"])
83
- cookies.assert_not_called()
83
+ urlopen.assert_not_called()
84
84
 
85
85
 
86
86
  if __name__ == "__main__":