patch-chat 0.1.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.
Files changed (146) hide show
  1. patch/__init__.py +20 -0
  2. patch/__main__.py +4 -0
  3. patch/_version.py +24 -0
  4. patch/analytics.py +260 -0
  5. patch/args.py +955 -0
  6. patch/args_formatter.py +228 -0
  7. patch/coders/__init__.py +32 -0
  8. patch/coders/architect_coder.py +47 -0
  9. patch/coders/architect_prompts.py +40 -0
  10. patch/coders/ask_coder.py +9 -0
  11. patch/coders/ask_prompts.py +41 -0
  12. patch/coders/base_coder.py +2548 -0
  13. patch/coders/base_prompts.py +60 -0
  14. patch/coders/chat_chunks.py +64 -0
  15. patch/coders/context_coder.py +53 -0
  16. patch/coders/context_prompts.py +75 -0
  17. patch/coders/edit_apply.py +6 -0
  18. patch/coders/editblock_coder.py +620 -0
  19. patch/coders/editblock_fenced_coder.py +10 -0
  20. patch/coders/editblock_fenced_prompts.py +143 -0
  21. patch/coders/editblock_func_coder.py +141 -0
  22. patch/coders/editblock_func_prompts.py +27 -0
  23. patch/coders/editblock_prompts.py +172 -0
  24. patch/coders/editor_diff_fenced_coder.py +9 -0
  25. patch/coders/editor_diff_fenced_prompts.py +11 -0
  26. patch/coders/editor_editblock_coder.py +8 -0
  27. patch/coders/editor_editblock_prompts.py +18 -0
  28. patch/coders/editor_whole_coder.py +8 -0
  29. patch/coders/editor_whole_prompts.py +10 -0
  30. patch/coders/patch_coder.py +731 -0
  31. patch/coders/patch_prompts.py +159 -0
  32. patch/coders/search_replace.py +757 -0
  33. patch/coders/shell.py +37 -0
  34. patch/coders/single_wholefile_func_coder.py +102 -0
  35. patch/coders/single_wholefile_func_prompts.py +27 -0
  36. patch/coders/udiff_coder.py +419 -0
  37. patch/coders/udiff_prompts.py +113 -0
  38. patch/coders/udiff_simple.py +14 -0
  39. patch/coders/udiff_simple_prompts.py +25 -0
  40. patch/coders/wholefile_coder.py +144 -0
  41. patch/coders/wholefile_func_coder.py +134 -0
  42. patch/coders/wholefile_func_prompts.py +27 -0
  43. patch/coders/wholefile_prompts.py +64 -0
  44. patch/commands.py +1668 -0
  45. patch/copypaste.py +70 -0
  46. patch/deprecated.py +126 -0
  47. patch/diffs.py +128 -0
  48. patch/dump.py +29 -0
  49. patch/editor.py +147 -0
  50. patch/exceptions.py +113 -0
  51. patch/format_settings.py +47 -0
  52. patch/gui.py +545 -0
  53. patch/history.py +143 -0
  54. patch/io.py +1209 -0
  55. patch/linter.py +304 -0
  56. patch/llm.py +47 -0
  57. patch/main.py +1466 -0
  58. patch/mdstream.py +243 -0
  59. patch/models.py +1342 -0
  60. patch/onboarding.py +428 -0
  61. patch/openrouter.py +128 -0
  62. patch/prompts.py +61 -0
  63. patch/queries/tree-sitter-language-pack/README.md +7 -0
  64. patch/queries/tree-sitter-language-pack/arduino-tags.scm +5 -0
  65. patch/queries/tree-sitter-language-pack/bash-tags.scm +8 -0
  66. patch/queries/tree-sitter-language-pack/c-tags.scm +9 -0
  67. patch/queries/tree-sitter-language-pack/chatito-tags.scm +16 -0
  68. patch/queries/tree-sitter-language-pack/clojure-tags.scm +7 -0
  69. patch/queries/tree-sitter-language-pack/commonlisp-tags.scm +122 -0
  70. patch/queries/tree-sitter-language-pack/cpp-tags.scm +15 -0
  71. patch/queries/tree-sitter-language-pack/csharp-tags.scm +26 -0
  72. patch/queries/tree-sitter-language-pack/d-tags.scm +26 -0
  73. patch/queries/tree-sitter-language-pack/dart-tags.scm +92 -0
  74. patch/queries/tree-sitter-language-pack/elisp-tags.scm +5 -0
  75. patch/queries/tree-sitter-language-pack/elixir-tags.scm +54 -0
  76. patch/queries/tree-sitter-language-pack/elm-tags.scm +19 -0
  77. patch/queries/tree-sitter-language-pack/gleam-tags.scm +41 -0
  78. patch/queries/tree-sitter-language-pack/go-tags.scm +42 -0
  79. patch/queries/tree-sitter-language-pack/java-tags.scm +20 -0
  80. patch/queries/tree-sitter-language-pack/javascript-tags.scm +88 -0
  81. patch/queries/tree-sitter-language-pack/lua-tags.scm +34 -0
  82. patch/queries/tree-sitter-language-pack/matlab-tags.scm +10 -0
  83. patch/queries/tree-sitter-language-pack/ocaml-tags.scm +115 -0
  84. patch/queries/tree-sitter-language-pack/ocaml_interface-tags.scm +98 -0
  85. patch/queries/tree-sitter-language-pack/pony-tags.scm +39 -0
  86. patch/queries/tree-sitter-language-pack/properties-tags.scm +5 -0
  87. patch/queries/tree-sitter-language-pack/python-tags.scm +14 -0
  88. patch/queries/tree-sitter-language-pack/r-tags.scm +21 -0
  89. patch/queries/tree-sitter-language-pack/racket-tags.scm +12 -0
  90. patch/queries/tree-sitter-language-pack/ruby-tags.scm +64 -0
  91. patch/queries/tree-sitter-language-pack/rust-tags.scm +60 -0
  92. patch/queries/tree-sitter-language-pack/solidity-tags.scm +43 -0
  93. patch/queries/tree-sitter-language-pack/swift-tags.scm +51 -0
  94. patch/queries/tree-sitter-language-pack/udev-tags.scm +20 -0
  95. patch/queries/tree-sitter-languages/README.md +24 -0
  96. patch/queries/tree-sitter-languages/bash-tags.scm +8 -0
  97. patch/queries/tree-sitter-languages/c-tags.scm +9 -0
  98. patch/queries/tree-sitter-languages/c_sharp-tags.scm +46 -0
  99. patch/queries/tree-sitter-languages/cpp-tags.scm +15 -0
  100. patch/queries/tree-sitter-languages/dart-tags.scm +91 -0
  101. patch/queries/tree-sitter-languages/elisp-tags.scm +8 -0
  102. patch/queries/tree-sitter-languages/elixir-tags.scm +54 -0
  103. patch/queries/tree-sitter-languages/elm-tags.scm +19 -0
  104. patch/queries/tree-sitter-languages/fortran-tags.scm +15 -0
  105. patch/queries/tree-sitter-languages/go-tags.scm +30 -0
  106. patch/queries/tree-sitter-languages/haskell-tags.scm +3 -0
  107. patch/queries/tree-sitter-languages/hcl-tags.scm +77 -0
  108. patch/queries/tree-sitter-languages/java-tags.scm +20 -0
  109. patch/queries/tree-sitter-languages/javascript-tags.scm +88 -0
  110. patch/queries/tree-sitter-languages/julia-tags.scm +60 -0
  111. patch/queries/tree-sitter-languages/kotlin-tags.scm +27 -0
  112. patch/queries/tree-sitter-languages/matlab-tags.scm +10 -0
  113. patch/queries/tree-sitter-languages/ocaml-tags.scm +115 -0
  114. patch/queries/tree-sitter-languages/ocaml_interface-tags.scm +98 -0
  115. patch/queries/tree-sitter-languages/php-tags.scm +26 -0
  116. patch/queries/tree-sitter-languages/python-tags.scm +12 -0
  117. patch/queries/tree-sitter-languages/ql-tags.scm +26 -0
  118. patch/queries/tree-sitter-languages/ruby-tags.scm +64 -0
  119. patch/queries/tree-sitter-languages/rust-tags.scm +60 -0
  120. patch/queries/tree-sitter-languages/scala-tags.scm +65 -0
  121. patch/queries/tree-sitter-languages/typescript-tags.scm +41 -0
  122. patch/queries/tree-sitter-languages/zig-tags.scm +3 -0
  123. patch/reasoning_tags.py +82 -0
  124. patch/repo.py +612 -0
  125. patch/repomap.py +859 -0
  126. patch/report.py +200 -0
  127. patch/resources/__init__.py +3 -0
  128. patch/resources/model-metadata.json +715 -0
  129. patch/resources/model-settings.yml +3128 -0
  130. patch/run_cmd.py +146 -0
  131. patch/scrape.py +316 -0
  132. patch/sendchat.py +61 -0
  133. patch/special.py +203 -0
  134. patch/urls.py +17 -0
  135. patch/utils.py +365 -0
  136. patch/versioncheck.py +113 -0
  137. patch/voice.py +200 -0
  138. patch/waiting.py +222 -0
  139. patch/watch.py +318 -0
  140. patch/watch_prompts.py +12 -0
  141. patch_chat-0.1.0.dist-info/METADATA +375 -0
  142. patch_chat-0.1.0.dist-info/RECORD +146 -0
  143. patch_chat-0.1.0.dist-info/WHEEL +5 -0
  144. patch_chat-0.1.0.dist-info/entry_points.txt +2 -0
  145. patch_chat-0.1.0.dist-info/licenses/LICENSE.txt +202 -0
  146. patch_chat-0.1.0.dist-info/top_level.txt +1 -0
patch/run_cmd.py ADDED
@@ -0,0 +1,146 @@
1
+ import os
2
+ import platform
3
+ import subprocess
4
+ import sys
5
+ from io import BytesIO
6
+
7
+ import pexpect
8
+ import psutil
9
+
10
+
11
+ def run_cmd(command, verbose=False, error_print=None, cwd=None):
12
+ try:
13
+ if sys.stdin.isatty() and hasattr(pexpect, "spawn") and platform.system() != "Windows":
14
+ return run_cmd_pexpect(command, verbose, cwd)
15
+
16
+ return run_cmd_subprocess(command, verbose, cwd)
17
+ except OSError as e:
18
+ error_message = f"Error occurred while running command '{command}': {str(e)}"
19
+ if error_print is None:
20
+ print(error_message)
21
+ else:
22
+ error_print(error_message)
23
+ return 1, error_message
24
+
25
+
26
+ def get_windows_parent_process_name():
27
+ try:
28
+ current_process = psutil.Process()
29
+ while True:
30
+ parent = current_process.parent()
31
+ if parent is None:
32
+ break
33
+ parent_name = parent.name().lower()
34
+ if parent_name in ["powershell.exe", "cmd.exe"]:
35
+ return parent_name
36
+ current_process = parent
37
+ return None
38
+ except Exception:
39
+ return None
40
+
41
+
42
+ def run_cmd_subprocess(command, verbose=False, cwd=None, encoding=sys.stdout.encoding):
43
+ if verbose:
44
+ print("Using run_cmd_subprocess:", command)
45
+
46
+ process = None
47
+ try:
48
+ shell = os.environ.get("SHELL", "/bin/sh")
49
+ parent_process = None
50
+
51
+ # Determine the appropriate shell
52
+ if platform.system() == "Windows":
53
+ parent_process = get_windows_parent_process_name()
54
+ if parent_process == "powershell.exe":
55
+ command = f"powershell -Command {command}"
56
+
57
+ if verbose:
58
+ print("Running command:", command)
59
+ print("SHELL:", shell)
60
+ if platform.system() == "Windows":
61
+ print("Parent process:", parent_process)
62
+
63
+ process = subprocess.Popen(
64
+ command,
65
+ stdout=subprocess.PIPE,
66
+ stderr=subprocess.STDOUT,
67
+ text=True,
68
+ shell=True,
69
+ encoding=encoding,
70
+ errors="replace",
71
+ bufsize=0, # Set bufsize to 0 for unbuffered output
72
+ universal_newlines=True,
73
+ cwd=cwd,
74
+ )
75
+
76
+ output = []
77
+ while True:
78
+ chunk = process.stdout.read(1)
79
+ if not chunk:
80
+ break
81
+ print(chunk, end="", flush=True) # Print the chunk in real-time
82
+ output.append(chunk) # Store the chunk for later use
83
+
84
+ process.wait()
85
+ return process.returncode, "".join(output)
86
+ except Exception as e:
87
+ return 1, str(e)
88
+ finally:
89
+ if process is not None:
90
+ if process.poll() is None:
91
+ try:
92
+ process.terminate()
93
+ process.wait(timeout=1)
94
+ except subprocess.TimeoutExpired:
95
+ process.kill()
96
+ process.wait()
97
+ except OSError:
98
+ process.wait()
99
+ if process.stdout:
100
+ process.stdout.close()
101
+
102
+
103
+ def run_cmd_pexpect(command, verbose=False, cwd=None):
104
+ """
105
+ Run a shell command interactively using pexpect, capturing all output.
106
+
107
+ :param command: The command to run as a string.
108
+ :param verbose: If True, print output in real-time.
109
+ :return: A tuple containing (exit_status, output)
110
+ """
111
+ if verbose:
112
+ print("Using run_cmd_pexpect:", command)
113
+
114
+ output = BytesIO()
115
+
116
+ def output_callback(b):
117
+ output.write(b)
118
+ return b
119
+
120
+ try:
121
+ # Use the SHELL environment variable, falling back to /bin/sh if not set
122
+ shell = os.environ.get("SHELL", "/bin/sh")
123
+ if verbose:
124
+ print("With shell:", shell)
125
+
126
+ if os.path.exists(shell):
127
+ # Use the shell from SHELL environment variable
128
+ if verbose:
129
+ print("Running pexpect.spawn with shell:", shell)
130
+ child = pexpect.spawn(shell, args=["-i", "-c", command], encoding="utf-8", cwd=cwd)
131
+ else:
132
+ # Fall back to spawning the command directly
133
+ if verbose:
134
+ print("Running pexpect.spawn without shell.")
135
+ child = pexpect.spawn(command, encoding="utf-8", cwd=cwd)
136
+
137
+ # Transfer control to the user, capturing output
138
+ child.interact(output_filter=output_callback)
139
+
140
+ # Wait for the command to finish and get the exit status
141
+ child.close()
142
+ return child.exitstatus, output.getvalue().decode("utf-8", errors="replace")
143
+
144
+ except (pexpect.ExceptionPexpect, TypeError, ValueError) as e:
145
+ error_msg = f"Error running command {command}: {e}"
146
+ return 1, error_msg
patch/scrape.py ADDED
@@ -0,0 +1,316 @@
1
+ #!/usr/bin/env python
2
+
3
+ import re
4
+ import sys
5
+
6
+ import pypandoc
7
+
8
+ from patch import __version__, urls, utils
9
+ from patch.dump import dump # noqa: F401
10
+
11
+ patch_user_agent = f"Patch/{__version__} +{urls.website}"
12
+ MAX_SCRAPED_CONTENT_BYTES = 5 * 1024 * 1024
13
+
14
+ # Playwright is nice because it has a simple way to install dependencies on most
15
+ # platforms.
16
+
17
+
18
+ def check_env():
19
+ try:
20
+ from playwright.sync_api import sync_playwright
21
+
22
+ has_pip = True
23
+ except ImportError:
24
+ has_pip = False
25
+
26
+ try:
27
+ with sync_playwright() as p:
28
+ p.chromium.launch()
29
+ has_chromium = True
30
+ except Exception:
31
+ has_chromium = False
32
+
33
+ return has_pip, has_chromium
34
+
35
+
36
+ def has_playwright():
37
+ has_pip, has_chromium = check_env()
38
+ return has_pip and has_chromium
39
+
40
+
41
+ def install_playwright(io):
42
+ has_pip, has_chromium = check_env()
43
+ if has_pip and has_chromium:
44
+ return True
45
+
46
+ pip_cmd = utils.get_pip_install(["patch-chat[playwright]"])
47
+ chromium_cmd = "-m playwright install --with-deps chromium"
48
+ chromium_cmd = [sys.executable] + chromium_cmd.split()
49
+
50
+ cmds = ""
51
+ if not has_pip:
52
+ cmds += " ".join(pip_cmd) + "\n"
53
+ if not has_chromium:
54
+ cmds += " ".join(chromium_cmd) + "\n"
55
+
56
+ text = f"""For the best web scraping, install Playwright:
57
+
58
+ {cmds}
59
+ See {urls.enable_playwright} for more info.
60
+ """
61
+
62
+ io.tool_output(text)
63
+ if not io.confirm_ask("Install playwright?", default="y"):
64
+ return
65
+
66
+ if not has_pip:
67
+ success, output = utils.run_install(pip_cmd)
68
+ if not success:
69
+ io.tool_error(output)
70
+ return
71
+
72
+ success, output = utils.run_install(chromium_cmd)
73
+ if not success:
74
+ io.tool_error(output)
75
+ return
76
+
77
+ return True
78
+
79
+
80
+ class Scraper:
81
+ pandoc_available = None
82
+ playwright_available = None
83
+ playwright_instructions_shown = False
84
+
85
+ # Public API...
86
+ def __init__(self, print_error=None, playwright_available=None, verify_ssl=True):
87
+ """
88
+ `print_error` - a function to call to print error/debug info.
89
+ `verify_ssl` - if False, disable SSL certificate verification when scraping.
90
+ """
91
+ if print_error:
92
+ self.print_error = print_error
93
+ else:
94
+ self.print_error = print
95
+
96
+ self.playwright_available = playwright_available
97
+ self.verify_ssl = verify_ssl
98
+
99
+ def scrape(self, url):
100
+ """
101
+ Scrape a url and turn it into readable markdown if it's HTML.
102
+ If it's plain text or non-HTML, return it as-is.
103
+
104
+ `url` - the URL to scrape.
105
+ """
106
+
107
+ if self.playwright_available:
108
+ content, mime_type = self.scrape_with_playwright(url)
109
+ else:
110
+ content, mime_type = self.scrape_with_httpx(url)
111
+
112
+ if not content:
113
+ self.print_error(f"Failed to retrieve content from {url}")
114
+ return None
115
+
116
+ # Check if the content is HTML based on MIME type or content
117
+ if (mime_type and mime_type.startswith("text/html")) or (
118
+ mime_type is None and self.looks_like_html(content)
119
+ ):
120
+ self.try_pandoc()
121
+ content = self.html_to_markdown(content)
122
+
123
+ return content
124
+
125
+ def looks_like_html(self, content):
126
+ """
127
+ Check if the content looks like HTML.
128
+ """
129
+ if isinstance(content, str):
130
+ # Check for common HTML tags
131
+ html_patterns = [
132
+ r"<!DOCTYPE\s+html",
133
+ r"<html",
134
+ r"<head",
135
+ r"<body",
136
+ r"<div",
137
+ r"<p>",
138
+ r"<a\s+href=",
139
+ ]
140
+ return any(re.search(pattern, content, re.IGNORECASE) for pattern in html_patterns)
141
+ return False
142
+
143
+ def content_too_large(self, size, url):
144
+ if size <= MAX_SCRAPED_CONTENT_BYTES:
145
+ return False
146
+
147
+ if MAX_SCRAPED_CONTENT_BYTES >= 1024 * 1024:
148
+ limit = f"{MAX_SCRAPED_CONTENT_BYTES // (1024 * 1024)} MB"
149
+ else:
150
+ limit = f"{MAX_SCRAPED_CONTENT_BYTES} bytes"
151
+ self.print_error(f"Content from {url} exceeds the {limit} scraping limit")
152
+ return True
153
+
154
+ # Internals...
155
+ def scrape_with_playwright(self, url):
156
+ import playwright # noqa: F401
157
+ from playwright.sync_api import Error as PlaywrightError
158
+ from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
159
+ from playwright.sync_api import sync_playwright
160
+
161
+ with sync_playwright() as p:
162
+ try:
163
+ browser = p.chromium.launch()
164
+ except Exception as e:
165
+ self.playwright_available = False
166
+ self.print_error(str(e))
167
+ return None, None
168
+
169
+ try:
170
+ context = browser.new_context(ignore_https_errors=not self.verify_ssl)
171
+ page = context.new_page()
172
+
173
+ user_agent = page.evaluate("navigator.userAgent")
174
+ user_agent = user_agent.replace("Headless", "")
175
+ user_agent = user_agent.replace("headless", "")
176
+ user_agent += " " + patch_user_agent
177
+
178
+ page.set_extra_http_headers({"User-Agent": user_agent})
179
+
180
+ response = None
181
+ try:
182
+ response = page.goto(url, wait_until="networkidle", timeout=5000)
183
+ except PlaywrightTimeoutError:
184
+ print(f"Page didn't quiesce, scraping content anyway: {url}")
185
+ response = None
186
+ except PlaywrightError as e:
187
+ self.print_error(f"Error navigating to {url}: {str(e)}")
188
+ return None, None
189
+
190
+ try:
191
+ content_size = page.evaluate(
192
+ "new TextEncoder().encode(document.documentElement.outerHTML).length"
193
+ )
194
+ if self.content_too_large(content_size, url):
195
+ return None, None
196
+ content = page.content()
197
+ mime_type = None
198
+ if response:
199
+ content_type = response.header_value("content-type")
200
+ if content_type:
201
+ mime_type = content_type.split(";")[0]
202
+ except PlaywrightError as e:
203
+ self.print_error(f"Error retrieving page content: {str(e)}")
204
+ content = None
205
+ mime_type = None
206
+ finally:
207
+ browser.close()
208
+
209
+ return content, mime_type
210
+
211
+ def scrape_with_httpx(self, url):
212
+ import httpx
213
+
214
+ headers = {"User-Agent": f"Mozilla./5.0 ({patch_user_agent})"}
215
+ try:
216
+ with httpx.Client(
217
+ headers=headers, verify=self.verify_ssl, follow_redirects=True
218
+ ) as client:
219
+ with client.stream("GET", url) as response:
220
+ response.raise_for_status()
221
+ content_length = response.headers.get("content-length")
222
+ if content_length and self.content_too_large(int(content_length), url):
223
+ return None, None
224
+
225
+ chunks = []
226
+ size = 0
227
+ for chunk in response.iter_bytes():
228
+ size += len(chunk)
229
+ if self.content_too_large(size, url):
230
+ return None, None
231
+ chunks.append(chunk)
232
+
233
+ encoding = response.encoding or "utf-8"
234
+ content = b"".join(chunks).decode(encoding, errors="replace")
235
+ mime_type = response.headers.get("content-type", "").split(";")[0]
236
+ return content, mime_type
237
+ except httpx.HTTPError as http_err:
238
+ self.print_error(f"HTTP error occurred: {http_err}")
239
+ except Exception as err:
240
+ self.print_error(f"An error occurred: {err}")
241
+ return None, None
242
+
243
+ def try_pandoc(self):
244
+ if self.pandoc_available:
245
+ return
246
+
247
+ try:
248
+ pypandoc.get_pandoc_version()
249
+ self.pandoc_available = True
250
+ return
251
+ except OSError:
252
+ pass
253
+
254
+ try:
255
+ pypandoc.download_pandoc(delete_installer=True)
256
+ except Exception as err:
257
+ self.print_error(f"Unable to install pandoc: {err}")
258
+ return
259
+
260
+ self.pandoc_available = True
261
+
262
+ def html_to_markdown(self, page_source):
263
+ from bs4 import BeautifulSoup
264
+
265
+ soup = BeautifulSoup(page_source, "html.parser")
266
+ soup = slimdown_html(soup)
267
+ page_source = str(soup)
268
+
269
+ if not self.pandoc_available:
270
+ return page_source
271
+
272
+ try:
273
+ md = pypandoc.convert_text(page_source, "markdown", format="html")
274
+ except OSError:
275
+ return page_source
276
+
277
+ md = re.sub(r"</div>", " ", md)
278
+ md = re.sub(r"<div>", " ", md)
279
+
280
+ md = re.sub(r"\n\s*\n", "\n\n", md)
281
+
282
+ return md
283
+
284
+
285
+ def slimdown_html(soup):
286
+ for svg in soup.find_all("svg"):
287
+ svg.decompose()
288
+
289
+ if soup.img:
290
+ soup.img.decompose()
291
+
292
+ for tag in soup.find_all(href=lambda x: x and x.startswith("data:")):
293
+ tag.decompose()
294
+
295
+ for tag in soup.find_all(src=lambda x: x and x.startswith("data:")):
296
+ tag.decompose()
297
+
298
+ for tag in soup.find_all(True):
299
+ for attr in list(tag.attrs):
300
+ if attr != "href":
301
+ tag.attrs.pop(attr, None)
302
+
303
+ return soup
304
+
305
+
306
+ def main(url):
307
+ scraper = Scraper(playwright_available=has_playwright())
308
+ content = scraper.scrape(url)
309
+ print(content)
310
+
311
+
312
+ if __name__ == "__main__":
313
+ if len(sys.argv) < 2:
314
+ print("Usage: python playw.py <URL>")
315
+ sys.exit(1)
316
+ main(sys.argv[1])
patch/sendchat.py ADDED
@@ -0,0 +1,61 @@
1
+ from patch.dump import dump # noqa: F401
2
+ from patch.utils import format_messages
3
+
4
+
5
+ def sanity_check_messages(messages):
6
+ """Check if messages alternate between user and assistant roles.
7
+ System messages can be interspersed anywhere.
8
+ Also verifies the last non-system message is from the user.
9
+ Returns True if valid, False otherwise."""
10
+ last_role = None
11
+ last_non_system_role = None
12
+
13
+ for msg in messages:
14
+ role = msg.get("role")
15
+ if role == "system":
16
+ continue
17
+
18
+ if last_role and role == last_role:
19
+ turns = format_messages(messages)
20
+ raise ValueError("Messages don't properly alternate user/assistant:\n\n" + turns)
21
+
22
+ last_role = role
23
+ last_non_system_role = role
24
+
25
+ # Ensure last non-system message is from user
26
+ return last_non_system_role == "user"
27
+
28
+
29
+ def ensure_alternating_roles(messages):
30
+ """Ensure messages alternate between 'assistant' and 'user' roles.
31
+
32
+ Inserts empty messages of the opposite role when consecutive messages
33
+ of the same role are found.
34
+
35
+ Args:
36
+ messages: List of message dictionaries with 'role' and 'content' keys.
37
+
38
+ Returns:
39
+ List of messages with alternating roles.
40
+ """
41
+ if not messages:
42
+ return messages
43
+
44
+ fixed_messages = []
45
+ prev_role = None
46
+
47
+ for msg in messages:
48
+ current_role = msg.get("role") # Get 'role', None if missing
49
+
50
+ # If current role same as previous, insert empty message
51
+ # of the opposite role
52
+ if current_role == prev_role:
53
+ if current_role == "user":
54
+ fixed_messages.append({"role": "assistant", "content": ""})
55
+ else:
56
+ fixed_messages.append({"role": "user", "content": ""})
57
+
58
+ fixed_messages.append(msg)
59
+ prev_role = current_role
60
+
61
+ return fixed_messages