main.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import json
  4. import argparse
  5. from rich.console import Console
  6. from rich.markdown import Markdown
  7. def duckduckgo_search(query, num_results=5):
  8. # Construct the DuckDuckGo URL for the search query
  9. url = f"https://html.duckduckgo.com/html/?q={query}"
  10. # Send a GET request to the DuckDuckGo search page
  11. headers = {
  12. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
  13. }
  14. response = requests.get(url, headers=headers)
  15. # Check if the request was successful
  16. if response.status_code != 200:
  17. print(f"Failed to retrieve search results. Status code: {response.status_code}")
  18. return []
  19. # Parse the HTML content using BeautifulSoup
  20. soup = BeautifulSoup(response.content, 'html.parser')
  21. # Find all result links (assuming they are in <a> tags with class "result__a")
  22. result_links = []
  23. for a_tag in soup.find_all('a', class_='result__a'):
  24. link = a_tag.get('href')
  25. if link:
  26. result_links.append(link)
  27. if len(result_links) >= num_results:
  28. break
  29. return result_links
  30. def extract_text_from_links(links, timeout=5):
  31. extracted_texts = []
  32. headers = {
  33. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
  34. }
  35. for link in links:
  36. try:
  37. response = requests.get(link, headers=headers, timeout=timeout)
  38. if response.status_code == 200:
  39. soup = BeautifulSoup(response.content, 'html.parser')
  40. # Extract text from the page
  41. text = soup.get_text(separator='\n', strip=True)
  42. extracted_texts.append((link, text))
  43. else:
  44. print(f"Failed to retrieve content from {link}. Status code: {response.status_code}")
  45. except requests.RequestException as e:
  46. print(f"An error occurred while fetching {link}: {e}")
  47. return extracted_texts
  48. def summarize_individual_texts(texts_and_urls, query, model, ollama_url="http://localhost:11434/api/generate"):
  49. summaries = []
  50. for url, text in texts_and_urls:
  51. prompt = f"Extract the relevant information from the following text with regards to the original \
  52. query: '{query}'\n\n{text}\n"
  53. payload = {
  54. "model": model,
  55. "prompt": prompt,
  56. "stream": False,
  57. "max_tokens": 1000,
  58. "options": {
  59. "num_ctx": 16384
  60. }
  61. }
  62. try:
  63. response = requests.post(ollama_url, json=payload)
  64. if response.status_code == 200:
  65. result = json.loads(response.text)["response"]
  66. summaries.append((url, result))
  67. else:
  68. print(f"Failed to get summary from Ollama server for {url}. Status code: {response.status_code}")
  69. except requests.RequestException as e:
  70. print(f"An error occurred while sending request to Ollama server for {url}: {e}")
  71. return summaries
  72. def summarize_with_ollama(texts_and_urls, query, model, ollama_url="http://localhost:11434/api/generate"):
  73. # Prepare the context and prompt
  74. context = "\n".join([f"URL: {url}\nText: {text}" for url, text in texts_and_urls])
  75. prompt = f"Summarize the following search results with regards to the original query: '{query}' \
  76. and include the full URLs as references where appropriate. Use markdown to format your response. Add unicode characters where it makes sense to make the summary colorful. \
  77. \n\n{context}"
  78. # Create the payload for the POST request
  79. payload = {
  80. "model": model,
  81. "prompt": prompt,
  82. "stream": False,
  83. "max_tokens": 1500,
  84. "options": {
  85. "num_ctx": 16384
  86. }
  87. }
  88. # Send the POST request to the Ollama server
  89. try:
  90. print("Processing")
  91. response = requests.post(ollama_url, json=payload)
  92. if response.status_code == 200:
  93. result = json.loads(response.text)["response"]
  94. return result
  95. else:
  96. print(f"Failed to get summary from Ollama server. Status code: {response.status_code}")
  97. return None
  98. except requests.RequestException as e:
  99. print(f"An error occurred while sending request to Ollama server: {e}")
  100. return None
  101. def optimize_search_query(query, query_model, ollama_url="http://localhost:11434/api/generate"):
  102. # Prepare the prompt for optimizing the search query
  103. prompt = f"Optimize the following natural language query to improve its effectiveness in a web search.\
  104. Make it very concise. Return just the optimized query no explanations. Query: '{query}'"
  105. # Create the payload for the POST request
  106. payload = {
  107. "model": query_model,
  108. "prompt": prompt,
  109. "stream": False,
  110. "max_tokens": 50
  111. }
  112. # Send the POST request to the Ollama server
  113. try:
  114. print("Optimizing search query")
  115. response = requests.post(ollama_url, json=payload)
  116. if response.status_code == 200:
  117. result = json.loads(response.text)["response"].strip()
  118. return result.strip('"')
  119. else:
  120. print(f"Failed to optimize search query from Ollama server. Status code: {response.status_code}")
  121. return query
  122. except requests.RequestException as e:
  123. print(f"An error occurred while sending request to Ollama server for optimizing the search query: {e}")
  124. return query
  125. def pretty_print_markdown(markdown_text):
  126. console = Console()
  127. md = Markdown(markdown_text)
  128. console.print(md)
  129. if __name__ == "__main__":
  130. # Set up argument parser
  131. parser = argparse.ArgumentParser(description="Search DuckDuckGo, extract text from results, and summarize with Ollama.")
  132. parser.add_argument("query", type=str, help="The search query to use on DuckDuckGo")
  133. parser.add_argument("--num_results", type=int, default=5, help="Number of search results to process (default: 5)")
  134. # Parse arguments
  135. args = parser.parse_args()
  136. original_query = args.query
  137. model = "command-r"
  138. #model = "qwq"
  139. #model = "qwen2.5:32b"
  140. query_model = model
  141. # Optimize the search query
  142. optimized_query = optimize_search_query(original_query, query_model)
  143. print(f"Original Query: {original_query}")
  144. print(f"Optimized Query: {optimized_query}")
  145. n = args.num_results # Number of results to extract
  146. links = duckduckgo_search(optimized_query, n)
  147. print(f"Top {n} search results:")
  148. for i, link in enumerate(links, start=1):
  149. print(f"{i}. {link}")
  150. texts_and_urls = extract_text_from_links(links)
  151. print("Summarizing individual search results")
  152. intermediate_summaries = summarize_individual_texts(texts_and_urls, original_query, model)
  153. final_summary = summarize_with_ollama(intermediate_summaries, original_query, model)
  154. if final_summary:
  155. print("\nFinal Summary of search results:\n")
  156. pretty_print_markdown(final_summary)