-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalefire-cli.py
More file actions
executable file
·2385 lines (2090 loc) · 107 KB
/
palefire-cli.py
File metadata and controls
executable file
·2385 lines (2090 loc) · 107 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Pale Fire CLI - Intelligent Knowledge Graph Search System
Command-line interface for ingesting episodes and querying the knowledge graph
with intelligent ranking and question-aware search capabilities.
"""
import argparse
import asyncio
import json
import logging
import os
import sys
import time
from datetime import datetime, timezone
from logging import INFO
from pathlib import Path
from typing import Optional
from dotenv import load_dotenv
# Load environment variables first
load_dotenv()
# Import configuration
import config
from graphiti_core import Graphiti
from graphiti_core.nodes import EpisodeType
from graphiti_core.llm_client.config import LLMConfig
from graphiti_core.llm_client.openai_generic_client import OpenAIGenericClient
from graphiti_core.embedder.openai import OpenAIEmbedder, OpenAIEmbedderConfig
from graphiti_core.cross_encoder.openai_reranker_client import OpenAIRerankerClient
# Import Pale Fire core modules
from modules import EntityEnricher, QuestionTypeDetector, KeywordExtractor
from agents import AIAgentDaemon
# Import utility functions
from utils.palefire_utils import (
search_episodes,
search_episodes_with_custom_ranking,
search_episodes_with_question_aware_ranking,
export_results_to_json,
clean_database,
)
# Import Ghostwriter Skill
try:
from modules.Ghostwriter import GhostwriterSkill
GHOSTWRITER_AVAILABLE = True
except ImportError:
GHOSTWRITER_AVAILABLE = False
# Configure logging from config
logging.basicConfig(
level=getattr(logging, config.LOG_LEVEL),
format=config.LOG_FORMAT,
datefmt=config.LOG_DATE_FORMAT,
)
logger = logging.getLogger(__name__)
# Global debug flag (set by CLI argument)
DEBUG = False
def debug_print(*args, **kwargs):
"""Print only if DEBUG is True."""
if DEBUG:
print(*args, **kwargs)
def load_episodes_from_file(filepath: str) -> list:
"""
Load episodes from a JSON file.
Expected format:
[
{
"content": "text or json object",
"type": "text" or "json",
"description": "description"
},
...
]
"""
try:
with open(filepath, 'r', encoding='utf-8') as f:
data = json.load(f)
# Convert type strings to EpisodeType
for episode in data:
type_str = episode.get('type', 'text')
if type_str == 'text':
episode['type'] = EpisodeType.text
elif type_str == 'json':
episode['type'] = EpisodeType.json
else:
logger.warning(f"Unknown episode type: {type_str}, defaulting to text")
episode['type'] = EpisodeType.text
return data
except FileNotFoundError:
logger.error(f"File not found: {filepath}")
sys.exit(1)
except json.JSONDecodeError as e:
logger.error(f"Invalid JSON in file {filepath}: {e}")
sys.exit(1)
except Exception as e:
logger.error(f"Error loading episodes: {e}")
sys.exit(1)
async def ingest_episodes(episodes_data: list, graphiti: Graphiti, use_ner: bool = True, debug: bool = False):
"""Ingest episodes into the knowledge graph with optional NER enrichment."""
try:
# Initialize the graph database
await graphiti.build_indices_and_constraints()
# Initialize NER enricher if requested
enricher = EntityEnricher(use_spacy=True) if use_ner else None
if debug:
debug_print('\n' + '='*80)
debug_print(f'📝 EPISODE INGESTION {"WITH NER ENRICHMENT" if use_ner else ""}')
debug_print('='*80)
for i, episode in enumerate(episodes_data):
if debug:
debug_print(f'\n[Episode {i}] Processing...')
if use_ner and enricher:
# Enrich episode with NER
enriched_episode = enricher.enrich_episode(episode)
# Display extracted entities
if debug and enriched_episode['entities_by_type']:
debug_print(f' ✓ Extracted {enriched_episode["entity_count"]} entities:')
for entity_type, entity_list in enriched_episode['entities_by_type'].items():
debug_print(f' - {entity_type}: {", ".join(entity_list[:5])}')
# Create enriched content
content = enricher.create_enriched_content(enriched_episode)
else:
content = (episode['content'] if isinstance(episode['content'], str)
else json.dumps(episode['content']))
# Add to Graphiti
await graphiti.add_episode(
name=f'Episode {i}',
episode_body=content,
source=episode['type'],
source_description=episode.get('description', 'No description'),
reference_time=datetime.now(timezone.utc),
)
if debug:
debug_print(f' ✓ Added to graph: Episode {i}')
if debug:
debug_print('\n' + '='*80)
debug_print(f'✅ INGESTION COMPLETE - {len(episodes_data)} episodes added')
debug_print('='*80)
finally:
await graphiti.close()
def extract_keywords_from_parsed_text(text: str, num_keywords: int = 20,
method: str = 'combined', verify_ner: bool = False,
deep: bool = False, blocksize: int = 1, debug: bool = False) -> Optional[list]:
"""
Extract keywords from parsed text using the AI Agent daemon.
Args:
text: Text to extract keywords from
num_keywords: Number of keywords to extract
method: Extraction method (tfidf, textrank, word_freq, combined, ner)
verify_ner: If True and method is 'ner', verify results using LLM
deep: If True and method is 'ner', process text sentence-by-sentence with ordered index
blocksize: Number of sentences per block when deep=True (default: 1 = sentence-by-sentence)
debug: Enable debug output
Returns:
List of keywords or None if extraction fails
"""
if not text or not text.strip():
return None
if debug:
import sys
debug_print('Extracting keywords from parsed text...', file=sys.stderr)
if verify_ner and method == 'ner':
debug_print('LLM verification enabled for NER results', file=sys.stderr)
if deep and method == 'ner':
debug_print(f'Deep mode enabled: processing sentence-by-sentence (blocksize={blocksize})', file=sys.stderr)
# Ensure daemon is running
ensure_daemon_running(debug=debug)
try:
from agents import get_daemon
daemon = get_daemon(use_spacy=True)
if not daemon.model_manager.is_initialized():
daemon.model_manager.initialize(use_spacy=True)
keywords = daemon.extract_keywords(
text,
num_keywords=num_keywords,
method=method,
verify_ner=verify_ner,
deep=deep,
blocksize=blocksize
)
return keywords
except Exception as e:
logger.warning(f"Failed to extract keywords: {e}")
if debug:
import sys
debug_print(f'Keyword extraction failed: {e}', file=sys.stderr)
return None
def extract_file_path_from_prompt(prompt: str) -> Optional[str]:
"""
Extract file path or URL from prompt using pattern matching (fallback when LLM is not available).
Args:
prompt: Natural language command
Returns:
Extracted file path/URL or None
"""
import re
import os
from urllib.parse import urlparse
# Pattern 0: URLs (http:// or https://)
url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+'
url_matches = re.findall(url_pattern, prompt)
if url_matches:
url = url_matches[0]
# Validate URL
try:
result = urlparse(url)
if all([result.scheme, result.netloc]):
return url
except Exception:
pass
# Pattern 1: Quoted paths (single or double quotes) - handles paths with spaces
# Match everything between quotes that ends with a file extension
quoted_pattern = r'["\']([^"\']*[^"\']+\.(?:pdf|txt|csv|xlsx|xls|ods|xlsm))["\']'
match = re.search(quoted_pattern, prompt)
if match:
path = match.group(1).strip()
if os.path.exists(path):
return path
# Try expanding ~
expanded_path = os.path.expanduser(path)
if os.path.exists(expanded_path):
return expanded_path
# Pattern 2: Absolute paths (starting with /) - handle paths with spaces by looking for file extension
# Match from / to the file extension, allowing spaces in between
abs_path_pattern = r'(/[^\s,]*[^\s,]+\.(?:pdf|txt|csv|xlsx|xls|ods|xlsm))'
matches = re.findall(abs_path_pattern, prompt)
for path in matches:
# Clean up any trailing punctuation
path = path.rstrip('.,;')
if os.path.exists(path):
return path
# Try expanding ~ and resolving
expanded_path = os.path.expanduser(path)
if os.path.exists(expanded_path):
return expanded_path
# Pattern 3: Absolute paths with spaces (more flexible)
# Look for /Users/ or /home/ or any absolute path ending with file extension
abs_path_flexible = r'(/[^\s,]+(?:/[^\s,]+)*\.(?:pdf|txt|csv|xlsx|xls|ods|xlsm))'
matches = re.findall(abs_path_flexible, prompt)
for path in matches:
path = path.rstrip('.,;')
if os.path.exists(path):
return path
# Pattern 4: Relative paths with extensions
rel_path_pattern = r'([^\s,]+\.(?:pdf|txt|csv|xlsx|xls|ods|xlsm))'
matches = re.findall(rel_path_pattern, prompt)
for match in matches:
# Skip if it's a URL or contains protocol
if '://' in match or match.startswith('http'):
continue
match = match.rstrip('.,;')
if os.path.exists(match):
return match
# Try with current directory
full_path = os.path.abspath(match)
if os.path.exists(full_path):
return full_path
return None
def detect_parser_from_prompt(prompt: str, debug: bool = False) -> Optional[dict]:
"""
Detect parser type and options from natural language prompt using LLM.
Args:
prompt: Natural language command (e.g., "parse PDF file example.pdf")
debug: Enable debug output
Returns:
Dictionary with parser detection results or None if detection fails
"""
try:
# First, try to extract file path using pattern matching (fallback)
extracted_path = extract_file_path_from_prompt(prompt)
# Try to use LLM for parser detection
llm_cfg = config.get_llm_config()
# Use LLM if API key is configured (works with both OpenAI and Ollama)
if llm_cfg.get('api_key'):
# Try to use simple Ollama client
try:
from utils.llm_client import SimpleOllamaClient
llm_client = SimpleOllamaClient(
model=llm_cfg['model'],
base_url=llm_cfg['base_url'],
api_key=llm_cfg['api_key']
)
# Load parser detection prompt
prompt_file = Path(__file__).parent / 'prompts' / 'system' / 'parser_detection_prompt.md'
if prompt_file.exists():
with open(prompt_file, 'r', encoding='utf-8') as f:
system_prompt = f.read()
else:
# Fallback prompt
system_prompt = """You are an intelligent file parser selector. Analyze user commands and determine which file parser to use.
Available parsers: pdf, txt, csv, spreadsheet (for .xlsx, .xls, .ods), url (for HTML pages from URLs).
Return JSON: {"parser": "pdf|txt|csv|spreadsheet|url", "file_path": "path_or_url", "file_type": "pdf|txt|csv|xlsx|xls|ods|url", "confidence": 0.0-1.0, "options": {}, "reasoning": "explanation"}"""
# Create detection prompt
detection_prompt = f"{system_prompt}\n\nUser command: {prompt}\n\nDetect parser and return JSON:"
if debug:
import sys
debug_print(f'Using LLM to detect parser from prompt: {prompt}', file=sys.stderr)
# Log the request to logs folder
try:
import time
from pathlib import Path
log_dir = Path(__file__).parent / 'logs'
log_dir.mkdir(parents=True, exist_ok=True)
timestamp = int(time.time())
log_file = log_dir / f"llm_request_parser_{timestamp}.txt"
with open(log_file, 'w', encoding='utf-8') as f:
f.write(detection_prompt)
except Exception as e:
logger.warning(f"Failed to log LLM request: {e}")
# Call LLM
response = llm_client.complete(
messages=[{"role": "user", "content": detection_prompt}],
temperature=0.1,
max_tokens=500
)
# Extract JSON from response
import re
json_match = re.search(r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}', response, re.DOTALL)
if json_match:
result = json.loads(json_match.group())
# Ensure file_path is set if LLM didn't extract it
if not result.get('file_path') and extracted_path:
result['file_path'] = extracted_path
if debug:
import sys
debug_print(f'Parser detection result: {result}', file=sys.stderr)
return result
else:
if debug:
import sys
debug_print(f'No JSON found in LLM response: {response}', file=sys.stderr)
# Fallback to pattern-based detection
if extracted_path:
return _create_fallback_detection(prompt, extracted_path, debug)
return None
except Exception as e:
if debug:
import sys
debug_print(f'LLM detection failed: {e}, using fallback', file=sys.stderr)
# Fallback to pattern-based detection
if extracted_path:
return _create_fallback_detection(prompt, extracted_path, debug)
return None
else:
# No LLM available, use pattern-based detection
if extracted_path:
return _create_fallback_detection(prompt, extracted_path, debug)
return None
except Exception as e:
if debug:
import sys
debug_print(f'Parser detection error: {e}', file=sys.stderr)
# Last resort: try pattern-based detection
extracted_path = extract_file_path_from_prompt(prompt)
if extracted_path:
return _create_fallback_detection(prompt, extracted_path, debug)
return None
def _create_fallback_detection(prompt: str, file_path: str, debug: bool = False) -> dict:
"""
Create parser detection result using pattern matching fallback.
Args:
prompt: Original prompt
file_path: Extracted file path or URL
debug: Enable debug output
Returns:
Detection result dictionary
"""
import re
from pathlib import Path
from urllib.parse import urlparse
# Check if it's a URL
try:
result = urlparse(file_path)
if all([result.scheme, result.netloc]):
# It's a URL
parser = 'url'
file_type = 'url'
confidence = 0.9
else:
# It's a file path
file_ext = Path(file_path).suffix.lower()
# Determine parser type from extension
parser_map = {
'.pdf': 'pdf',
'.txt': 'txt',
'.text': 'txt',
'.csv': 'csv',
'.xlsx': 'spreadsheet',
'.xls': 'spreadsheet',
'.xlsm': 'spreadsheet',
'.ods': 'spreadsheet',
}
parser = parser_map.get(file_ext, None)
if not parser:
return None
file_type = file_ext.lstrip('.')
confidence = 0.8
except Exception:
# Fallback: try as file path
file_ext = Path(file_path).suffix.lower()
parser_map = {
'.pdf': 'pdf',
'.txt': 'txt',
'.text': 'txt',
'.csv': 'csv',
'.xlsx': 'spreadsheet',
'.xls': 'spreadsheet',
'.xlsm': 'spreadsheet',
'.ods': 'spreadsheet',
}
parser = parser_map.get(file_ext, None)
if not parser:
return None
file_type = file_ext.lstrip('.')
confidence = 0.8
# Extract options from prompt
options = {}
# Extract max_pages for PDF
if parser == 'pdf':
pages_match = re.search(r'(?:first|only|max|limit).*?(\d+).*?page', prompt, re.IGNORECASE)
if pages_match:
options['max_pages'] = int(pages_match.group(1))
# Extract delimiter for CSV
if parser == 'csv':
delimiter_match = re.search(r'(?:with|using|delimiter).*?([;,\t])', prompt, re.IGNORECASE)
if delimiter_match:
options['delimiter'] = delimiter_match.group(1)
# Extract sheet names for spreadsheet
if parser == 'spreadsheet':
sheet_match = re.search(r"(?:only|sheet|sheets).*?['\"]([^'\"]+)['\"]", prompt, re.IGNORECASE)
if sheet_match:
options['sheet_names'] = [sheet_match.group(1)]
# Extract timeout for URL
if parser == 'url':
timeout_match = re.search(r'(?:timeout|wait).*?(\d+)', prompt, re.IGNORECASE)
if timeout_match:
options['timeout'] = int(timeout_match.group(1))
# Extract keyword extraction options (works for all parsers)
keyword_patterns = [
r'extract.*?keyword',
r'get.*?keyword',
r'find.*?keyword',
r'keyword.*?extraction',
r'extract.*?all.*?keyword',
]
extract_keywords = any(re.search(pattern, prompt, re.IGNORECASE) for pattern in keyword_patterns)
if extract_keywords:
options['extract_keywords'] = True
# Try to extract number of keywords
num_keywords_match = re.search(r'(?:extract|get|find).*?(\d+).*?keyword', prompt, re.IGNORECASE)
if num_keywords_match:
options['num_keywords'] = int(num_keywords_match.group(1))
elif 'all keywords' in prompt.lower():
# "all keywords" means extract many keywords
options['num_keywords'] = 50 # Default for "all"
# Check if NER method is requested
ner_patterns = [
r'keyword.*?ner',
r'keyword.*?with.*?ner',
r'ner.*?keyword',
r'named.*?entity.*?keyword',
r'extract.*?keyword.*?with.*?ner',
r'use.*?ner.*?for.*?keyword',
]
if any(re.search(pattern, prompt, re.IGNORECASE) for pattern in ner_patterns):
options['keywords_method'] = 'ner'
# Check if verification is requested
verify_patterns = [
r'verify',
r'and.*?verify',
r'verify.*?ner',
r'ner.*?verify',
r'verify.*?result',
r'check.*?result',
r'validate',
]
if any(re.search(pattern, prompt, re.IGNORECASE) for pattern in verify_patterns):
options['verify_ner'] = True
result = {
'parser': parser,
'file_path': file_path,
'file_type': file_ext.lstrip('.'),
'confidence': 0.8 if file_ext in parser_map else 0.5,
'options': options,
'reasoning': f'Pattern-based detection: file extension {file_ext} maps to {parser} parser'
}
if debug:
import sys
debug_print(f'Fallback detection result: {result}', file=sys.stderr)
return result
def parse_file_command(file_path: str, output_file: Optional[str] = None,
extract_keywords: bool = False, keywords_method: str = 'combined',
num_keywords: int = 20, verify_ner: bool = False, deep: bool = False,
blocksize: int = 1, debug: bool = False, prompt: Optional[str] = None, **parser_options):
"""Parse a file using the appropriate parser."""
try:
from agents.parsers import get_parser
# If prompt is provided, try to detect parser and options from it
if prompt:
detection_result = detect_parser_from_prompt(prompt, debug=debug)
if detection_result and detection_result.get('confidence', 0) > 0.5:
# Use detected parser and file path
detected_parser = detection_result.get('parser')
detected_file_path = detection_result.get('file_path') or file_path
detected_options = detection_result.get('options', {})
if debug:
import sys
debug_print(f'Detected parser: {detected_parser}, file: {detected_file_path}, options: {detected_options}', file=sys.stderr)
# Override file_path if detected
if detected_file_path and detected_file_path != file_path:
file_path = detected_file_path
# Merge detected options with provided options
parser_options.update(detected_options)
# Map parser type to actual parser
if detected_parser == 'pdf':
from agents.parsers import PDFParser
parser = PDFParser()
elif detected_parser == 'csv':
from agents.parsers import CSVParser
parser = CSVParser()
elif detected_parser == 'txt':
from agents.parsers import TXTParser
parser = TXTParser()
elif detected_parser == 'spreadsheet':
from agents.parsers import SpreadsheetParser
parser = SpreadsheetParser()
elif detected_parser == 'url':
from agents.parsers import URLParser
timeout = detected_options.get('timeout', 30)
parser = URLParser(timeout=timeout)
else:
# Fallback to auto-detection
parser = get_parser(file_path)
else:
# Fallback to auto-detection
if debug:
import sys
debug_print(f'Parser detection failed or low confidence, using auto-detection', file=sys.stderr)
parser = get_parser(file_path)
else:
if debug:
import sys
debug_print(f'Parsing file: {file_path}', file=sys.stderr)
parser = get_parser(file_path)
# Parse file with options
result = parser.parse(file_path, **parser_options)
if not result.success:
logger.error(f"Parsing failed: {result.error}")
print(json.dumps({'error': result.error}, indent=2))
return
output = result.to_dict()
# Extract keywords if requested
if extract_keywords:
if debug:
import sys
debug_print('Extracting keywords from parsed text...', file=sys.stderr)
# Ensure daemon is running
ensure_daemon_running(debug=debug)
try:
from agents import get_daemon
daemon = get_daemon(use_spacy=True)
if not daemon.model_manager.is_initialized():
daemon.model_manager.initialize(use_spacy=True)
keywords = daemon.extract_keywords(
result.text,
num_keywords=num_keywords,
method=keywords_method,
verify_ner=verify_ner,
deep=deep,
blocksize=blocksize
)
output['keywords'] = keywords
# Add verified field if NER verification was performed
if verify_ner and keywords_method == 'ner':
output['verified'] = True
except Exception as e:
logger.warning(f"Failed to extract keywords: {e}")
if debug:
import sys
debug_print(f'Keyword extraction failed: {e}', file=sys.stderr)
# Output results
if output_file:
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(output, f, indent=2, ensure_ascii=False)
if debug:
import sys
debug_print(f'✅ Results saved to {output_file}', file=sys.stderr)
else:
print(json.dumps(output, indent=2, ensure_ascii=False))
except ValueError as e:
logger.error(f"Parser error: {e}")
print(json.dumps({'error': str(e)}, indent=2))
except Exception as e:
logger.error(f"Error parsing file: {e}", exc_info=True)
print(json.dumps({'error': f"Error parsing file: {str(e)}"}, indent=2))
def parse_txt_command(file_path: str, encoding: str = 'utf-8',
output_file: Optional[str] = None, debug: bool = False,
prompt: Optional[str] = None,
extract_keywords: bool = False, keywords_method: str = 'combined',
num_keywords: int = 20, verify_ner: bool = False, deep: bool = False, blocksize: int = 1):
"""Parse a text file."""
try:
from agents.parsers import TXTParser
# If prompt is provided, try to extract file path from it
if prompt:
extracted_path = extract_file_path_from_prompt(prompt)
if extracted_path and (not file_path or not os.path.exists(file_path)):
file_path = extracted_path
if debug:
import sys
debug_print(f'Extracted file path from prompt: {file_path}', file=sys.stderr)
# Validate file path
if not file_path:
print(json.dumps({'error': 'No file path provided. Please specify a file or use --prompt with a file path.', 'success': False}, indent=2))
return
if not os.path.exists(file_path):
print(json.dumps({'error': f'File not found: {file_path}', 'success': False}, indent=2))
return
parser = TXTParser(encoding=encoding)
result = parser.parse(file_path, encoding=encoding)
output = result.to_dict()
# Extract keywords if requested
if extract_keywords:
keywords = extract_keywords_from_parsed_text(
result.text,
num_keywords=num_keywords,
method=keywords_method,
verify_ner=verify_ner,
deep=deep,
blocksize=blocksize,
debug=debug
)
if keywords:
output['keywords'] = keywords
# Add verified field if NER verification was performed
if verify_ner and keywords_method == 'ner':
output['verified'] = True
if output_file:
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(output, f, indent=2, ensure_ascii=False)
else:
print(json.dumps(output, indent=2, ensure_ascii=False))
except Exception as e:
logger.error(f"Error parsing text file: {e}", exc_info=True)
print(json.dumps({'error': f"Error parsing file: {str(e)}"}, indent=2))
def parse_csv_command(file_path: str, delimiter: str = ',', include_headers: bool = True,
output_file: Optional[str] = None, debug: bool = False,
prompt: Optional[str] = None,
extract_keywords: bool = False, keywords_method: str = 'combined',
num_keywords: int = 20, verify_ner: bool = False, deep: bool = False, blocksize: int = 1):
"""Parse a CSV file."""
try:
from agents.parsers import CSVParser
# If prompt is provided, try to detect parser and options from it
if prompt:
# First, try to extract file path from prompt
extracted_path = extract_file_path_from_prompt(prompt)
if extracted_path and (not file_path or not os.path.exists(file_path)):
file_path = extracted_path
if debug:
import sys
debug_print(f'Extracted file path from prompt: {file_path}', file=sys.stderr)
# Then try LLM detection for options
detection_result = detect_parser_from_prompt(prompt, debug=debug)
if detection_result and detection_result.get('confidence', 0) > 0.5:
detected_file_path = detection_result.get('file_path')
detected_options = detection_result.get('options', {})
if detected_file_path and os.path.exists(detected_file_path):
file_path = detected_file_path
if 'delimiter' in detected_options:
delimiter = detected_options['delimiter']
if 'include_headers' in detected_options:
include_headers = detected_options['include_headers']
if debug:
import sys
debug_print(f'Using detected file path: {file_path}, delimiter: {delimiter}', file=sys.stderr)
# Validate file path
if not file_path:
print(json.dumps({'error': 'No file path provided. Please specify a file or use --prompt with a file path.', 'success': False}, indent=2))
return
if not os.path.exists(file_path):
print(json.dumps({'error': f'File not found: {file_path}', 'success': False}, indent=2))
return
parser = CSVParser(delimiter=delimiter)
result = parser.parse(file_path, delimiter=delimiter, include_headers=include_headers)
output = result.to_dict()
# Extract keywords if requested
if extract_keywords:
keywords = extract_keywords_from_parsed_text(
result.text,
num_keywords=num_keywords,
method=keywords_method,
verify_ner=verify_ner,
deep=deep,
blocksize=blocksize,
debug=debug
)
if keywords:
output['keywords'] = keywords
# Add verified field if NER verification was performed
if verify_ner and keywords_method == 'ner':
output['verified'] = True
if output_file:
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(output, f, indent=2, ensure_ascii=False)
else:
print(json.dumps(output, indent=2, ensure_ascii=False))
except Exception as e:
logger.error(f"Error parsing CSV file: {e}", exc_info=True)
print(json.dumps({'error': f"Error parsing file: {str(e)}"}, indent=2))
def parse_pdf_command(file_path: str, max_pages: Optional[int] = None,
extract_tables: bool = True, output_file: Optional[str] = None,
debug: bool = False, prompt: Optional[str] = None,
extract_keywords: bool = False, keywords_method: str = 'combined',
num_keywords: int = 20, verify_ner: bool = False, deep: bool = False, blocksize: int = 1):
"""Parse a PDF file."""
try:
from agents.parsers import PDFParser
# If prompt is provided, try to detect parser and options from it
if prompt:
# First, always try to extract file path from prompt (pattern matching)
extracted_path = extract_file_path_from_prompt(prompt)
if extracted_path and (not file_path or not os.path.exists(file_path)):
file_path = extracted_path
if debug:
import sys
debug_print(f'Extracted file path from prompt: {file_path}', file=sys.stderr)
# Then try LLM detection for parser type and options
detection_result = detect_parser_from_prompt(prompt, debug=debug)
if detection_result and detection_result.get('confidence', 0) > 0.5:
detected_file_path = detection_result.get('file_path')
detected_options = detection_result.get('options', {})
# Use detected file path if available and current path is invalid
if detected_file_path and os.path.exists(detected_file_path):
file_path = detected_file_path
if 'max_pages' in detected_options and detected_options['max_pages']:
max_pages = detected_options['max_pages']
if 'extract_tables' in detected_options:
extract_tables = detected_options['extract_tables']
# Extract keyword extraction options from detection
if 'extract_keywords' in detected_options and detected_options['extract_keywords']:
extract_keywords = True
if 'num_keywords' in detected_options:
num_keywords = detected_options['num_keywords']
if 'keywords_method' in detected_options:
keywords_method = detected_options['keywords_method']
if 'verify_ner' in detected_options and detected_options['verify_ner']:
verify_ner = True
if debug:
import sys
debug_print(f'Using detected file path: {file_path}, max_pages: {max_pages}, extract_keywords: {extract_keywords}, verify_ner: {verify_ner}', file=sys.stderr)
else:
# Fallback: try pattern-based keyword detection
import re
keyword_patterns = [
r'extract.*?keyword',
r'get.*?keyword',
r'find.*?keyword',
r'keyword.*?extraction',
r'extract.*?all.*?keyword',
]
if any(re.search(pattern, prompt, re.IGNORECASE) for pattern in keyword_patterns):
extract_keywords = True
num_keywords_match = re.search(r'(?:extract|get|find).*?(\d+).*?keyword', prompt, re.IGNORECASE)
if num_keywords_match:
num_keywords = int(num_keywords_match.group(1))
elif 'all keywords' in prompt.lower():
num_keywords = 50 # Default for "all"
# Check if NER method is requested
ner_patterns = [
r'keyword.*?ner',
r'keyword.*?with.*?ner',
r'ner.*?keyword',
r'named.*?entity.*?keyword',
r'extract.*?keyword.*?with.*?ner',
r'use.*?ner.*?for.*?keyword',
]
if any(re.search(pattern, prompt, re.IGNORECASE) for pattern in ner_patterns):
keywords_method = 'ner'
# Check if verification is requested
verify_patterns = [
r'verify',
r'and.*?verify',
r'verify.*?ner',
r'ner.*?verify',
r'verify.*?result',
r'check.*?result',
r'validate',
]
if any(re.search(pattern, prompt, re.IGNORECASE) for pattern in verify_patterns):
verify_ner = True
if debug:
import sys
debug_print(f'Detected keyword extraction from prompt: extract_keywords={extract_keywords}, num_keywords={num_keywords}, method={keywords_method}, verify_ner={verify_ner}', file=sys.stderr)
# Validate file path
if not file_path:
print(json.dumps({'error': 'No file path provided. Please specify a file or use --prompt with a file path.', 'success': False}, indent=2))
return
if not os.path.exists(file_path):
print(json.dumps({'error': f'File not found: {file_path}', 'success': False}, indent=2))
return
parser = PDFParser()
result = parser.parse(file_path, max_pages=max_pages, extract_tables=extract_tables)
output = result.to_dict()
# Extract keywords if requested
if extract_keywords:
keywords = extract_keywords_from_parsed_text(
result.text,
num_keywords=num_keywords,
method=keywords_method,
verify_ner=verify_ner,
deep=deep,
blocksize=blocksize,
debug=debug
)
if keywords:
output['keywords'] = keywords
# Add verified field if NER verification was performed
if verify_ner and keywords_method == 'ner':
output['verified'] = True
if output_file:
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(output, f, indent=2, ensure_ascii=False)
else:
print(json.dumps(output, indent=2, ensure_ascii=False))
except Exception as e:
logger.error(f"Error parsing PDF file: {e}", exc_info=True)
print(json.dumps({'error': f"Error parsing file: {str(e)}"}, indent=2))
def parse_spreadsheet_command(file_path: str, sheet_names: Optional[list] = None,
include_headers: bool = True, output_file: Optional[str] = None,
debug: bool = False, prompt: Optional[str] = None,
extract_keywords: bool = False, keywords_method: str = 'combined',
num_keywords: int = 20, verify_ner: bool = False, deep: bool = False, blocksize: int = 1):
"""Parse a spreadsheet file."""
try:
from agents.parsers import SpreadsheetParser
# If prompt is provided, try to detect parser and options from it
if prompt:
detection_result = detect_parser_from_prompt(prompt, debug=debug)
if detection_result and detection_result.get('confidence', 0) > 0.5:
detected_file_path = detection_result.get('file_path') or file_path
detected_options = detection_result.get('options', {})
if detected_file_path:
file_path = detected_file_path
if 'sheet_names' in detected_options and detected_options['sheet_names']:
sheet_names = detected_options['sheet_names']
if debug:
import sys
debug_print(f'Using detected file path: {file_path}, sheet_names: {sheet_names}', file=sys.stderr)
parser = SpreadsheetParser()
result = parser.parse(file_path, sheet_names=sheet_names, include_headers=include_headers)
output = result.to_dict()
# Extract keywords if requested
if extract_keywords:
keywords = extract_keywords_from_parsed_text(
result.text,
num_keywords=num_keywords,
method=keywords_method,
verify_ner=verify_ner,
deep=deep,
blocksize=blocksize,
debug=debug
)
if keywords: