|
| 1 | +""" |
| 2 | +Extracts unresolved Google Drive comments and their surrounding document context into Markdown files. |
| 3 | +
|
| 4 | +Workflow: |
| 5 | +1. Iterates through a list of document names and IDs (DOCS). |
| 6 | +2. Processes documents concurrently using asyncio and a semaphore (limit 5). |
| 7 | +3. For each document: |
| 8 | + a. Lists comments using 'gws drive comments list'. |
| 9 | + b. Filters for unresolved comments. |
| 10 | + c. Exports the document as 'text/plain' via 'gws drive files export' to a temporary file. |
| 11 | + d. Matches the comment's 'quotedFileContent' against the exported text. |
| 12 | + - Normalization: Unescapes HTML and collapses all whitespace (including \u000b) for robust matching. |
| 13 | + - Context: If a match is found (>3 chars), extracts 3 lines before and after. |
| 14 | + e. Formats the results as Markdown with code blocks for context and bulleted lists for replies. |
| 15 | + f. Saves to '[Document Name].md', sanitizing slashes in filenames and cleaning up temp files. |
| 16 | +""" |
| 17 | + |
| 18 | +import asyncio |
| 19 | +import json |
| 20 | +import subprocess |
| 21 | +import os |
| 22 | +import html |
| 23 | +import re |
| 24 | + |
| 25 | +# List of documents to process |
| 26 | +DOCS = [ |
| 27 | + ("Beancount - Trading with Beancount", "1WjARst_cSxNE-Lq6JnJ5CC41T3WndEsiMw4d46r2694"), |
| 28 | + ("Beancount - Tracking Medical Claims", "1NyATal9CRrBDsII6sLdwCNNv0qcJmcPxYpNrlnjCjp8"), |
| 29 | + ("Beancount - Language Syntax", "1wAMVrKIA2qtRGmoVDSUBJGmYZSygUaR0uOMW1GV3YE0"), |
| 30 | + ("Beancount - Contributions", "1Z37bQ45wDtjTPaMQ_x-f33p1trH9fNosEAUgbQXwp30"), |
| 31 | + ("Beancount - Precision & Tolerances", "1lgHxUUEY-UVEgoF6cupz2f_7v7vEF7fiJyiSlYYlhOo"), |
| 32 | + ("Beancount - Query Language", "1s0GOZMcrKKCLlP29MD7kHO4L88evrwWdIO0p4EwRBE0"), |
| 33 | + ("Beancount - How Inventories Work", "11a9bIoNuxpSOth3fmfuIFzlZtpTJbvw-bPaQCnezQJs"), |
| 34 | + ("Beancount - Tutorial & Example", "1G-gsmwK551lSyuHboVLW3xbLhh99JfoKIbNnZSJxteE"), |
| 35 | + ("Beancount - Comparison / Differences", "1dW2vIjaXVJAf9hr7GlZVe3fJOkM-MtlVjvCO1ZpNLmg"), |
| 36 | + ("Beancount - Price in Beancount", "1thYRAMell_QT1Da1F_laprSs6BlROZjyK_h3V8qHW9c"), |
| 37 | + ("Beancount - Importing External Data", "11EwQdujzEo2cxqaF5PgxCEZXWfKKQCYSMfdJowp_1S8"), |
| 38 | + ("Beancount - Getting Started", "1P5At-z1sP8rgwYLHso5sEy3u4rMnIUDDgob9Y_BYuWE"), |
| 39 | + ("Beancount - Running & Reports", "1e44jtLyVRl2H2Pj4K3WUc66otAlTOFOc90-tsrFEQdo"), |
| 40 | + ("Beancount - Install", "1FqyrTPwiHVLyncWTf3v5TcooCu9z5JRX8Nm41lVZi0U"), |
| 41 | + ("Beancount - The Double-Entry Counting Method", "100tGcA4blh6KSXPRGCZpUlyxaRUwFHEvnz_k9DyZFn4"), |
| 42 | + ("Beancount - Motivation", "1e4Vz3wZB_8-ZcAwIFde8X5CjzKshE4-OXtVVHm4RQ8s"), |
| 43 | + ("Beancount - C++ version: Install", "1WwZYqsp28Uuk5eFqHQ1u1zqdjghymy8S_Yo-OJENoa4"), |
| 44 | + ("Beangulp - Importing External Data", "1hBfsHZcoHgz5rvhCdP42g2FJ5ouycIMV4H1tfgXpwBU"), |
| 45 | + ("Beancount - Index", "1RaondTJCS_IUPBHFNdT8oqFKJjVJDsfsn6JEjBG04eA"), |
| 46 | + ("Beancount - Beangulp", "1O42HgYQBQEna6YpobTqszSgTGnbRX7RdjmzR2xumfjs"), |
| 47 | + ("Beancount - History and Credits", "17wTH7aKnN_7-6nCxsOad6zIQfHwQgJUdI02RjzQuNi8"), |
| 48 | + ("Beancount - Cookbook", "1Tss0IEzEyAPuKSGeNsfNgb0BfiW2ZHyP5nCFBW1uWlk"), |
| 49 | + ("Beancount - Symbology", "1_52VhapAuR-ej4yB8rFovA8MyMmF8IOcqO44apsdtKU"), |
| 50 | + ("Beancount - C++ version: Dependencies", "10R-msZljuqFY8nckUnR1jVxMX1ol7rJUCMZo7w7QUQs"), |
| 51 | + ("Beancount - Cookbook - How We Share Expenses", "1MjSpGoJVdgyg8rhKD9otSKo4iSD2VkSYELMWDBbsBiU"), |
| 52 | + ("Beancount - Cookbook - HealthCare Expenses", "16RKEl1NJ3qg8VU9vKRRvgIv3CyGs0_4ASS4lD5iBFTw"), |
| 53 | + ("Beancount - Vnext: Booking Rules Redesign", "1H0UDD1cKenraIMe40PbdMgnqJdeqI6yKv0og51mXk-0"), |
| 54 | + ("Beancount - C++ version: Changes from V2", "1Ia4zYmkB6I6IbWPRlcZYYuMS1ZI55T99dp9LiMJqXCE"), |
| 55 | + ("Beancount - Vnext: Goals & Design", "1qPdNXaz5zuDQ8M9uoZFyyFis7hA0G55BEfhWhrVBsfc"), |
| 56 | + ("Beancount - Rust version", "1M1GM4NvXWdSoIfUpexc5b3m72Up2-drqn3gP8TCCySk"), |
| 57 | + ("Beancount - Vnext: How to Use the API", "1hl7g_e2Bgb6mOEJ3nlleWUkmItJXjcXEUbNOM3tLiUk"), |
| 58 | + ("Beancount - For Cryptocurrencies", "1taN9lbcNDf8bKgDwprWOhuaOsOgALZzmsfvec-rdaSk"), |
| 59 | + ("Beancount - Calculating Portfolio Returns", "1nPsMIunLnDvdsg6TSsd0PZb7jngojNpFlqnaX36WRp8"), |
| 60 | + ("Beancount - Payee, Subaccount or Asset", "17_u_cYxeXVsCV4GmaubK_xsTQl_H9rP87E_vnZHKNb0"), |
| 61 | + ("Beancount - User Requests & Prioritization", "1uHonpRkbZ5wMCoZtzCBSBrl959Ciy4gq4aTB7A-m8Uk"), |
| 62 | + ("Beancount - Syntax Cheat Sheet", "1M4GwF6BkcXyVVvj4yXBJMX7YFXpxlxo95W6CpU3uWVc"), |
| 63 | + ("Johnny", "18AfWSRhQ1sWr0S4rd0GvQFy_7bXxCod-TC1qNrPHCEM"), |
| 64 | + ("Beancount - The Beancount Universe", "1K8l4eU3bBFaU1U_7sV9-3XRD0YDXPQP4b8t7ehk5cVk"), |
| 65 | + ("Beancount - Trading Options", "1YcFo17bO98TSxcIOehBQ_zDqm59CI1yyit7tP_Wdjyc"), |
| 66 | + ("Beancount - Ulque", "1hJCIpkl1ngF5v-a63s5HBPZX4aoXMQORR-EJjAQDUvo"), |
| 67 | + ("Beancount - Exporting your Portfolio (New)", "1mNyE_ONuyEkF_I2l6V_AoAU5HJgI654AOBhHsnNPPqw"), |
| 68 | + ("LedgerHub - Post-Mortem", "1Bln8Zo11Cvez2rdEgpnM-oBHC1B6uPC18Qm7ulobolM"), |
| 69 | + ("TRASH", "1lkFz-cUz_j_R3aHNp786ZB9fWcN7wxoZzdSnZ5Z3ILg"), |
| 70 | + ("Exposing Protocol Buffers from C++", "1xiFw7OLsFux8wWrZ3JqofuIsjIcIr4RuYrh7NdgMjeE"), |
| 71 | + ("Questions for haberman@", "1Z9edeb4oldExImuxq4-4ZnW0WnuYQRsstiaBwJuyL8c"), |
| 72 | + ("Beancount - Parsed Comments", "1yestw21g4AEMNrIUsBuOaxucfz3_7eMAR6NYnVnTzV0"), |
| 73 | + ("Beancount - Cookbook - Sharing Expenses", "1FRcJqUfeAMQO6KjG94w6rF7VajMGJaFplmF1Wu0rCHY"), |
| 74 | + ("Beancount - Design Doc", "1N7HDXuNWgLG2PqFS4Kkgv5LzAAtU6c97UVNT7tdTIjA"), |
| 75 | + ("Beancount - Scripting & Plugins", "1QftxNvQPdH-MikMBHupftU6F4IsNZP5FlFh1LCbVgk8"), |
| 76 | + ("LedgerHub - Design Doc", "11u1sWv7H7Ykbc7ayS4M9V3yKqcuTY7LJ3n1tgnEN2Hk"), |
| 77 | + ("Beancount - Cookbook - Vesting", "1mHNlNMTZsKPMjP_qQmedoizZFQy1-GzlR2lX5zy_0ok"), |
| 78 | + ("Beancount - Calculating Portfolio Returns (Old)", "1vEFB44-HFqydYVJXA-QxT4AN0K5xHHfSkhTmRSCPkac"), |
| 79 | + ("Universal Lightweight Query Engine", "1uemjVaZrFa-nnPNojZVMyLYTpWCT17cTPSOkCofuNFg"), |
| 80 | + ("Beancount - Migration to Git", "1B_HgWkrg36B7QoilWbLd2BAEDee8n-WGd7Mh5cT1NLQ"), |
| 81 | + ("Beancount - Solving the Conversions Problem", "1rW7zQyMiv8hKZ0993pwQiu5vTxzEOQf_Q67GvVk6zu0"), |
| 82 | + ("Beancount - Cookbook - In-Progress", "1lAKWL7hbeYVuDd1v5SiccEmj220XNumz8we8znNdx58"), |
| 83 | + ("Beancount - Exporting your Portfolio", "1eZIDRmQZxR6cmDyOJf7U3BnCm4PDMah2twxYFfKPJtM"), |
| 84 | + ("Beancount - Self-Reductions", "16dKnXJ7KZhemPs5NPHmSTNCV7LUPrMD9jFgiV79Npb8"), |
| 85 | + ("Beancount - Options Reference", "1_-T_BvDtUjj9M7liZMNSkrL8pgC60TGMBlYCiV1e4ZM"), |
| 86 | + ("Beancount - Snippets", "191zP806Wlkhv5aKSQ-eYIG9dKbQhw1a5cZRRxh1m6cI"), |
| 87 | + ("Beancount - Interpolation", "1t2AgozNduKEMsFoEfy_i1C_lKKVLArzsnpdzG_IUey4"), |
| 88 | + ("LedgerHub - Instructions & Status", "1vnvqQNGaHOM3opRnEZspvALpv-G6fVQq0bSgAchVpuk"), |
| 89 | + ("Beancount - Documents about CAs", "1m71AKKWKl9j3YhRLFK8C1AHaxXY_VkTFv_aJEQb1ng8"), |
| 90 | + ("Beancount - Contributor Agreement", "1B4KQrUzyhtxzm_RojXLYHL_0xqRRLuR8gxreu3mwv-4"), |
| 91 | + ("Beancount - Contributing", "1nIj00U8wI7rcOo5wHEG54cyQz4X6GoW7G8FWJmF1hrI"), |
| 92 | + ("Beancount - Fetching Prices", "1EZCP8VX3cOuyp2CKECfsq0LAfaXcHTVr7-EKIsRJBa8"), |
| 93 | + ("Beancount - Developer Guidelines", "1l6YmKIPUsucrooofdrollO6Re2rTPJA9KigoS8OBluk"), |
| 94 | + ("Beancount - Converting", "1tkoUeSfZyEhEGdXHwYp5vBrSrNDgC4FVXhReSWsILlw"), |
| 95 | + ("Beancount - Custom Application: Return on Property", "1SnR7BdE2VXFTMEvnkhAd9PwXu_AxytTYpiS1LjXdP0E"), |
| 96 | + ("Beancount - Using Equity Accounts", "1H6C4YNPSe8GvC9Pe4Mp84q7ErPwI2AlZrFfKuNq-TG4"), |
| 97 | + ("Beancount - Wash Sales", "1hByM4oV9Q9BS66SimgRov1gcD72ykn4acmFbWj5g66M"), |
| 98 | + ("Accounting - Links", "1fzsGnYz3r8lthpU6A2O6eddNREOnl5-85zcwsXwMTyU"), |
| 99 | + ("Beancount - Proposal - Inventory Booking Improvements", "1F8IJ_7fMHZ75XFPocMokLxVZczAhrBRBVN9uMhQFCZ4"), |
| 100 | + ("Beancount - Proposal - Rounding & Precision", "1MY2JMiiXUmcwsOT0CkiK-fCo0ZE7nbr8uTcTL50b6X4"), |
| 101 | + ("Beancount - Proposal - Fund Accounting", "1nf_yCiLuewVCEjkXq9Kd9SqbZGWqcs0v0pT5xQnkyzs"), |
| 102 | + ("Beancount - Proposal - Balance Assertions", "1vyemZFox47IZjuBrT2RjhSHZyTgloYOUeJb73RxMRD0"), |
| 103 | + ("Beancount - Proposal - Settlement Dates", "1x0qqWGRHi02ef-FtUW172SHkdJ8quOZD-Xli7r4Nl_k"), |
| 104 | +] |
| 105 | + |
| 106 | +# Limit concurrency |
| 107 | +semaphore = asyncio.Semaphore(5) |
| 108 | + |
| 109 | +def normalize(text): |
| 110 | + if not text: |
| 111 | + return "" |
| 112 | + # Unescape HTML entities |
| 113 | + text = html.unescape(text) |
| 114 | + # Replace \u000b and other whitespace with standard space for matching |
| 115 | + text = re.sub(r'[\s\u000b]+', ' ', text).strip() |
| 116 | + return text |
| 117 | + |
| 118 | +def get_context(full_text, quoted_text, lines_before=3, lines_after=3): |
| 119 | + normalized_full = normalize(full_text) |
| 120 | + normalized_quoted = normalize(quoted_text) |
| 121 | + |
| 122 | + if not normalized_quoted or len(normalized_quoted) < 4: |
| 123 | + # Don't try to find context for very short strings (like "TODO") |
| 124 | + return None |
| 125 | + |
| 126 | + if normalized_quoted not in normalized_full: |
| 127 | + return None |
| 128 | + |
| 129 | + lines = full_text.splitlines() |
| 130 | + |
| 131 | + # Pre-normalize all lines for matching |
| 132 | + normalized_lines = [normalize(line) for line in lines] |
| 133 | + |
| 134 | + # Try to find which line(s) contain the quoted text |
| 135 | + for i, n_line in enumerate(normalized_lines): |
| 136 | + if normalized_quoted in n_line: |
| 137 | + start = max(0, i - lines_before) |
| 138 | + end = min(len(lines), i + lines_after + 1) |
| 139 | + return "\n".join(lines[start:end]) |
| 140 | + |
| 141 | + # If not found in a single line, it might span multiple lines. |
| 142 | + # Let's search for the first 20 chars of normalized_quoted. |
| 143 | + first_part = normalized_quoted[:20] |
| 144 | + for i, n_line in enumerate(normalized_lines): |
| 145 | + if first_part in n_line: |
| 146 | + start = max(0, i - lines_before) |
| 147 | + end = min(len(lines), i + lines_after + 1) |
| 148 | + return "\n".join(lines[start:end]) |
| 149 | + |
| 150 | + return None |
| 151 | + |
| 152 | +async def process_doc(name, file_id): |
| 153 | + async with semaphore: |
| 154 | + # 1. List comments |
| 155 | + params = { |
| 156 | + "fileId": file_id, |
| 157 | + "fields": "comments(content,author(displayName),resolved,quotedFileContent,replies(content,author(displayName)))" |
| 158 | + } |
| 159 | + cmd = ["gws", "drive", "comments", "list", "--params", json.dumps(params)] |
| 160 | + |
| 161 | + proc = await asyncio.create_subprocess_exec( |
| 162 | + *cmd, |
| 163 | + stdout=asyncio.subprocess.PIPE, |
| 164 | + stderr=asyncio.subprocess.PIPE |
| 165 | + ) |
| 166 | + stdout, stderr = await proc.communicate() |
| 167 | + |
| 168 | + if proc.returncode != 0: |
| 169 | + return |
| 170 | + |
| 171 | + try: |
| 172 | + data = json.loads(stdout.decode()) |
| 173 | + comments = data.get("comments", []) |
| 174 | + unresolved = [c for c in comments if not c.get("resolved", False)] |
| 175 | + |
| 176 | + if not unresolved: |
| 177 | + return |
| 178 | + |
| 179 | + # 2. Export doc for context |
| 180 | + export_params = { |
| 181 | + "fileId": file_id, |
| 182 | + "mimeType": "text/plain" |
| 183 | + } |
| 184 | + tmp_filename = f"tmp_{file_id}.txt" |
| 185 | + export_cmd = ["gws", "drive", "files", "export", "--params", json.dumps(export_params), "-o", tmp_filename] |
| 186 | + |
| 187 | + export_proc = await asyncio.create_subprocess_exec( |
| 188 | + *export_cmd, |
| 189 | + stdout=asyncio.subprocess.PIPE, |
| 190 | + stderr=asyncio.subprocess.PIPE |
| 191 | + ) |
| 192 | + await export_proc.communicate() |
| 193 | + |
| 194 | + doc_text = "" |
| 195 | + if os.path.exists(tmp_filename): |
| 196 | + with open(tmp_filename, "r", encoding="utf-8", errors="ignore") as f: |
| 197 | + doc_text = f.read() |
| 198 | + os.remove(tmp_filename) |
| 199 | + |
| 200 | + md_content = [] |
| 201 | + for c in unresolved: |
| 202 | + quoted_obj = c.get("quotedFileContent", {}) |
| 203 | + quoted_value = quoted_obj.get("value", "") |
| 204 | + |
| 205 | + context = None |
| 206 | + if doc_text and quoted_value: |
| 207 | + context = get_context(doc_text, quoted_value) |
| 208 | + |
| 209 | + # Always show the highlighted selection |
| 210 | + unescaped_quote = html.unescape(quoted_value) if quoted_value else "[No selection]" |
| 211 | + md_content.append(f"> {unescaped_quote}\n\n") |
| 212 | + |
| 213 | + # Show context block if found |
| 214 | + if context: |
| 215 | + md_content.append(f"```text\n{context}\n```\n\n") |
| 216 | + |
| 217 | + author = c.get("author", {}).get("displayName", "Unknown") |
| 218 | + content = c.get("content", "") |
| 219 | + md_content.append(f"**{author}**: {content}\n") |
| 220 | + |
| 221 | + for r in c.get("replies", []): |
| 222 | + r_author = r.get("author", {}).get("displayName", "Unknown") |
| 223 | + r_content = r.get("content", "") |
| 224 | + md_content.append(f" - **{r_author}**: {r_content}\n") |
| 225 | + |
| 226 | + md_content.append("\n---\n") |
| 227 | + |
| 228 | + if md_content: |
| 229 | + # Replace slashes in filename |
| 230 | + safe_name = name.replace("/", "_").replace("\\", "_") |
| 231 | + filename = f"{safe_name}.md" |
| 232 | + with open(filename, "w") as f: |
| 233 | + f.write("".join(md_content)) |
| 234 | + print(f"Created: {filename}") |
| 235 | + |
| 236 | + except Exception as e: |
| 237 | + print(f"Exception processing {name}: {e}") |
| 238 | + |
| 239 | +async def main(): |
| 240 | + tasks = [process_doc(name, file_id) for name, file_id in DOCS] |
| 241 | + await asyncio.gather(*tasks) |
| 242 | + |
| 243 | +if __name__ == "__main__": |
| 244 | + asyncio.run(main()) |
0 commit comments