This repository was archived by the owner on Feb 5, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfilter_by_folder.py
More file actions
354 lines (281 loc) · 10.1 KB
/
filter_by_folder.py
File metadata and controls
354 lines (281 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env python3
"""
Filter Granola Documents by Folder (Document List)
This script helps you filter and list documents by folder/document list.
"""
import json
import argparse
import logging
from pathlib import Path
from collections import defaultdict
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def load_document_lists(output_dir):
"""
Load document lists information from saved document_lists.json
Args:
output_dir: Directory containing document_lists.json
Returns:
dict: List ID to list info mapping
"""
lists_path = output_dir / "document_lists.json"
list_map = {}
if not lists_path.exists():
logger.warning(f"No document_lists.json found at {lists_path}")
return list_map
try:
with open(lists_path, 'r') as f:
lists_data = json.load(f)
# Handle different response formats
lists = []
if isinstance(lists_data, list):
lists = lists_data
elif isinstance(lists_data, dict):
if "lists" in lists_data:
lists = lists_data["lists"]
elif "document_lists" in lists_data:
lists = lists_data["document_lists"]
for doc_list in lists:
list_id = doc_list.get("id")
if list_id:
list_map[list_id] = doc_list
except Exception as e:
logger.error(f"Error loading document lists: {e}")
return list_map
def get_all_documents(output_dir):
"""
Load all document metadata from the output directory
Args:
output_dir: Directory containing document folders
Returns:
list: List of document metadata dictionaries
"""
documents = []
if not output_dir.exists():
logger.error(f"Output directory {output_dir} does not exist")
return documents
for doc_folder in output_dir.iterdir():
if not doc_folder.is_dir():
continue
metadata_path = doc_folder / "metadata.json"
if not metadata_path.exists():
continue
try:
with open(metadata_path, 'r') as f:
metadata = json.load(f)
documents.append(metadata)
except Exception as e:
logger.error(f"Error reading {metadata_path}: {e}")
return documents
def filter_by_folder(documents, folder_id):
"""
Filter documents by folder ID
Args:
documents: List of document metadata
folder_id: Folder ID to filter by
Returns:
list: Filtered documents
"""
filtered = []
for doc in documents:
folders = doc.get("folders", [])
for folder in folders:
if folder.get("id") == folder_id:
filtered.append(doc)
break
return filtered
def filter_by_folder_name(documents, folder_name):
"""
Filter documents by folder name (case-insensitive partial match)
Args:
documents: List of document metadata
folder_name: Folder name to search for
Returns:
list: Filtered documents
"""
filtered = []
for doc in documents:
folders = doc.get("folders", [])
for folder in folders:
if folder_name.lower() in folder.get("name", "").lower():
filtered.append(doc)
break
return filtered
def group_by_folder(documents):
"""
Group documents by folder
Args:
documents: List of document metadata
Returns:
dict: Folder ID to list of documents mapping
"""
groups = defaultdict(list)
no_folder = []
for doc in documents:
folders = doc.get("folders", [])
if not folders:
no_folder.append(doc)
else:
for folder in folders:
folder_id = folder.get("id", "unknown")
groups[folder_id].append({
"doc": doc,
"folder_name": folder.get("name", "Unknown")
})
return dict(groups), no_folder
def main():
parser = argparse.ArgumentParser(
description="Filter and list Granola documents by folder (document list)"
)
parser.add_argument(
"output_dir",
type=str,
help="Directory containing saved documents"
)
parser.add_argument(
"--folder-id",
type=str,
help="Filter by specific folder ID"
)
parser.add_argument(
"--folder-name",
type=str,
help="Filter by folder name (case-insensitive partial match)"
)
parser.add_argument(
"--list-folders",
action="store_true",
help="List all folders and their document counts"
)
parser.add_argument(
"--no-folder",
action="store_true",
help="Show documents that are not in any folder"
)
args = parser.parse_args()
output_path = Path(args.output_dir)
if not output_path.exists():
logger.error(f"Output directory {output_path} does not exist")
return
# Load folder information
folder_map = load_document_lists(output_path)
# Load all documents
logger.info(f"Loading documents from {output_path}...")
documents = get_all_documents(output_path)
logger.info(f"Loaded {len(documents)} documents")
print()
if args.list_folders:
# List all folders with document counts
groups, no_folder = group_by_folder(documents)
print("=" * 80)
print("Folders Summary")
print("=" * 80)
print()
# Sort by document count
sorted_groups = sorted(groups.items(), key=lambda x: len(x[1]), reverse=True)
for folder_id, docs in sorted_groups:
folder_name = docs[0]["folder_name"] if docs else "Unknown"
folder_info = folder_map.get(folder_id, {})
print(f"Folder: {folder_name}")
print(f" ID: {folder_id}")
print(f" Documents: {len(docs)}")
if folder_info:
if "created_at" in folder_info:
print(f" Created: {folder_info.get('created_at')}")
if "workspace_id" in folder_info:
print(f" Workspace ID: {folder_info.get('workspace_id')}")
print()
if no_folder:
print(f"Documents not in any folder: {len(no_folder)}")
print()
elif args.no_folder:
# Show documents not in any folder
_, no_folder = group_by_folder(documents)
print("=" * 80)
print("Documents Not in Any Folder")
print("=" * 80)
print()
if not no_folder:
print("All documents are organized in folders!")
else:
for i, doc in enumerate(no_folder, 1):
print(f"{i}. {doc.get('title', 'Untitled')}")
print(f" ID: {doc.get('document_id', 'N/A')}")
print(f" Created: {doc.get('created_at', 'N/A')}")
print()
print(f"Total: {len(no_folder)} documents")
elif args.folder_id:
# Filter by folder ID
filtered = filter_by_folder(documents, args.folder_id)
folder_info = folder_map.get(args.folder_id, {})
folder_name = folder_info.get("name") or folder_info.get("title", "Unknown Folder")
print("=" * 80)
print(f"Documents in Folder: {folder_name}")
print(f"Folder ID: {args.folder_id}")
print("=" * 80)
print()
if not filtered:
print("No documents found in this folder.")
else:
for i, doc in enumerate(filtered, 1):
print(f"{i}. {doc.get('title', 'Untitled')}")
print(f" ID: {doc.get('document_id', 'N/A')}")
print(f" Created: {doc.get('created_at', 'N/A')}")
print(f" Updated: {doc.get('updated_at', 'N/A')}")
print()
print(f"Total: {len(filtered)} documents")
elif args.folder_name:
# Filter by folder name
filtered = filter_by_folder_name(documents, args.folder_name)
print("=" * 80)
print(f"Documents with Folder Name Matching: '{args.folder_name}'")
print("=" * 80)
print()
if not filtered:
print(f"No documents found in folders matching '{args.folder_name}'")
else:
# Group by exact folder
by_folder = defaultdict(list)
for doc in filtered:
for folder in doc.get("folders", []):
if args.folder_name.lower() in folder.get("name", "").lower():
by_folder[folder.get("name")].append(doc)
for folder_name, docs in by_folder.items():
print(f"\nFolder: {folder_name}")
print(f"Documents: {len(docs)}")
print("-" * 80)
for i, doc in enumerate(docs, 1):
print(f" {i}. {doc.get('title', 'Untitled')}")
print(f" ID: {doc.get('document_id', 'N/A')}")
print()
print(f"Total: {len(filtered)} documents")
else:
# No filter - show all documents grouped by folder
groups, no_folder = group_by_folder(documents)
print("=" * 80)
print("All Documents Grouped by Folder")
print("=" * 80)
print()
for folder_id, docs in groups.items():
folder_name = docs[0]["folder_name"] if docs else "Unknown"
print(f"Folder: {folder_name}")
print(f"ID: {folder_id}")
print(f"Documents: {len(docs)}")
print("-" * 80)
for i, item in enumerate(docs[:5], 1): # Show first 5
doc = item["doc"]
print(f" {i}. {doc.get('title', 'Untitled')}")
if len(docs) > 5:
print(f" ... and {len(docs) - 5} more")
print()
if no_folder:
print(f"\nDocuments not in any folder: {len(no_folder)}")
for i, doc in enumerate(no_folder[:5], 1):
print(f" {i}. {doc.get('title', 'Untitled')}")
if len(no_folder) > 5:
print(f" ... and {len(no_folder) - 5} more")
if __name__ == "__main__":
main()