-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·356 lines (285 loc) · 10.9 KB
/
main.py
File metadata and controls
executable file
·356 lines (285 loc) · 10.9 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
355
356
#!/usr/bin/env python3
"""
Claude Code Transcript Explorer - Main Entry Point
A comprehensive tool for searching, analyzing, and exploring Claude Code conversation transcripts.
"""
import sys
import os
import argparse
import logging
from pathlib import Path
# Add current directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from ui.app import create_interface
from core.data_loader import TranscriptLoader
from core.search_engine import SearchEngine, SearchIndex, SearchQuery, SearchMode
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def main():
"""Main entry point for the application."""
parser = argparse.ArgumentParser(
description='Claude Code Transcript Explorer - Search and analyze conversation transcripts'
)
parser.add_argument(
'--mode',
choices=['gui', 'cli', 'export'],
default='gui',
help='Run mode: gui (Gradio interface), cli (command line), or export (batch export)'
)
parser.add_argument(
'--data-path',
type=str,
default='/home/ygg/.claude/projects',
help='Path to transcript data directory'
)
parser.add_argument(
'--port',
type=int,
default=7860,
help='Port for Gradio server (GUI mode only)'
)
parser.add_argument(
'--share',
action='store_true',
help='Create a public share link (GUI mode only)'
)
parser.add_argument(
'--search',
type=str,
help='Search query (CLI mode only)'
)
parser.add_argument(
'--export-format',
choices=['json', 'csv', 'markdown'],
default='json',
help='Export format for results'
)
parser.add_argument(
'--output',
type=str,
help='Output file path for exports'
)
parser.add_argument(
'--cache-dir',
type=str,
default='/tmp/transcript_explorer_cache',
help='Directory for caching search indices'
)
args = parser.parse_args()
try:
if args.mode == 'gui':
run_gui(args)
elif args.mode == 'cli':
run_cli(args)
elif args.mode == 'export':
run_export(args)
except KeyboardInterrupt:
logger.info("Application terminated by user")
sys.exit(0)
except Exception as e:
logger.error(f"Application error: {e}")
sys.exit(1)
def run_gui(args):
"""Run the Gradio GUI interface.
Args:
args: Command line arguments
"""
logger.info("Starting Gradio interface...")
# Create and launch the interface
app = create_interface()
logger.info(f"Launching server on port {args.port}")
app.launch(
server_name="0.0.0.0",
server_port=args.port,
share=args.share,
show_error=True
)
def run_cli(args):
"""Run command-line search.
Args:
args: Command line arguments
"""
if not args.search:
print("Error: --search query required for CLI mode")
sys.exit(1)
logger.info("Running CLI search...")
# Initialize components
loader = TranscriptLoader(args.data_path)
search_engine = SearchEngine(SearchIndex(args.cache_dir))
# Check for cached index
if not search_engine.index.load_index_from_cache():
print("Loading transcript files...")
messages, conversations = loader.load_all_files(show_progress=True)
print("Building search index...")
search_engine.index.build_index(messages, conversations)
else:
print("Using cached search index")
# Still need to load messages and conversations for results
messages, conversations = loader.load_all_files(show_progress=True)
search_engine.index.messages = messages
search_engine.index.conversations = conversations
# Create search query
query = SearchQuery(
text=args.search,
mode=SearchMode.FUZZY,
limit=50
)
# Execute search
print(f"\nSearching for: '{args.search}'...")
results = search_engine.search(query)
# Display results
if not results:
print("No results found.")
else:
print(f"\nFound {len(results)} results:\n")
print("-" * 80)
for i, result in enumerate(results[:10], 1):
msg = result.message
print(f"\n{i}. [{msg.role.value.upper()}] {msg.timestamp.strftime('%Y-%m-%d %H:%M')}")
print(f" Session: {msg.session_id[:8]}...")
print(f" Score: {result.score:.2f}")
print(f" Content: {result.get_context_snippet(200)}")
if msg.tool_calls:
tools = ", ".join([tc.tool_name for tc in msg.tool_calls])
print(f" Tools: {tools}")
print("-" * 80)
if len(results) > 10:
print(f"\n... and {len(results) - 10} more results")
# Export if requested
if args.output:
export_results(results, args.export_format, args.output)
print(f"\nResults exported to: {args.output}")
def run_export(args):
"""Run batch export of all transcripts.
Args:
args: Command line arguments
"""
logger.info("Running batch export...")
# Initialize loader
loader = TranscriptLoader(args.data_path)
print("Loading transcript files...")
messages, conversations = loader.load_all_files(show_progress=True)
# Get statistics
stats = loader.get_statistics()
print(f"\nLoaded {stats['total_messages']} messages from {stats['total_conversations']} conversations")
# Determine output path
if args.output:
output_path = Path(args.output)
else:
output_path = Path(f"transcript_export.{args.export_format}")
# Export based on format
if args.export_format == 'json':
import json
export_data = {
'statistics': stats,
'conversations': []
}
for conv_id, conv in conversations.items():
conv_data = {
'session_id': conv_id,
'start_time': conv.start_time.isoformat(),
'end_time': conv.end_time.isoformat(),
'duration_minutes': conv.get_duration_minutes(),
'total_messages': conv.total_messages,
'messages': [msg.to_dict() for msg in conv.messages]
}
export_data['conversations'].append(conv_data)
with open(output_path, 'w') as f:
json.dump(export_data, f, indent=2, default=str)
elif args.export_format == 'csv':
import pandas as pd
rows = []
for msg in messages:
rows.append({
'timestamp': msg.timestamp.isoformat(),
'session_id': msg.session_id,
'role': msg.role.value,
'type': msg.type.value,
'content': msg.content[:1000], # Truncate long content
'tools': ', '.join([tc.tool_name for tc in msg.tool_calls]),
'model': msg.model or '',
'cwd': msg.cwd or ''
})
df = pd.DataFrame(rows)
df.to_csv(output_path, index=False)
elif args.export_format == 'markdown':
with open(output_path, 'w') as f:
f.write("# Claude Code Transcript Export\n\n")
f.write(f"Generated: {datetime.now().isoformat()}\n\n")
f.write("## Statistics\n\n")
for key, value in stats.items():
if isinstance(value, list):
value = len(value)
f.write(f"- **{key}**: {value}\n")
f.write("\n## Conversations\n\n")
for conv_id, conv in list(conversations.items())[:10]: # Limit to 10 for markdown
f.write(f"### Session {conv_id[:8]}...\n\n")
f.write(f"- Start: {conv.start_time}\n")
f.write(f"- Duration: {conv.get_duration_minutes():.1f} minutes\n")
f.write(f"- Messages: {conv.total_messages}\n\n")
for msg in conv.messages[:5]: # First 5 messages
f.write(f"**[{msg.role.value.upper()}]** {msg.timestamp.strftime('%H:%M:%S')}\n\n")
f.write(f"```\n{msg.content[:500]}\n```\n\n")
if conv.total_messages > 5:
f.write(f"... and {conv.total_messages - 5} more messages\n\n")
f.write("---\n\n")
print(f"Export complete: {output_path}")
print(f"File size: {output_path.stat().st_size / 1024 / 1024:.2f} MB")
def export_results(results, format, output_path):
"""Export search results to file.
Args:
results: Search results to export
format: Export format
output_path: Output file path
"""
from datetime import datetime
import json
import pandas as pd
if format == 'json':
export_data = []
for result in results:
msg = result.message
export_data.append({
'timestamp': msg.timestamp.isoformat(),
'session_id': msg.session_id,
'role': msg.role.value,
'content': msg.content,
'score': result.score,
'matched_fields': result.matched_fields,
'tools': [tc.tool_name for tc in msg.tool_calls]
})
with open(output_path, 'w') as f:
json.dump(export_data, f, indent=2, default=str)
elif format == 'csv':
rows = []
for result in results:
msg = result.message
rows.append({
'timestamp': msg.timestamp.isoformat(),
'session_id': msg.session_id,
'role': msg.role.value,
'content': msg.content[:500],
'score': result.score,
'tools': ', '.join([tc.tool_name for tc in msg.tool_calls])
})
df = pd.DataFrame(rows)
df.to_csv(output_path, index=False)
elif format == 'markdown':
with open(output_path, 'w') as f:
f.write("# Search Results\n\n")
f.write(f"Query executed: {datetime.now().isoformat()}\n\n")
for i, result in enumerate(results, 1):
msg = result.message
f.write(f"## Result {i}\n\n")
f.write(f"- **Score**: {result.score:.2f}\n")
f.write(f"- **Timestamp**: {msg.timestamp}\n")
f.write(f"- **Role**: {msg.role.value}\n")
f.write(f"- **Session**: {msg.session_id[:8]}...\n\n")
f.write(f"**Content:**\n```\n{msg.content}\n```\n\n")
f.write("---\n\n")
if __name__ == "__main__":
main()