-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
1754 lines (1563 loc) · 93.9 KB
/
main.py
File metadata and controls
1754 lines (1563 loc) · 93.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
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
"""
Main entry point for HTML Agent Analysis System
"""
import os
import json
import logging
import argparse
from pathlib import Path
from typing import List, Dict, Any, Optional
from config import Settings
from agents import Orchestrator, AnalyzerAgent, CodeGeneratorAgent, CodeValidatorAgent, MarkdownConverterAgent
from utils import HTMLParser, VisualAnalyzer, URLDownloader
from utils.logger import setup_logging
from utils.checkpoint import CheckpointManager
# Setup beautiful logging
logger = setup_logging(log_dir="logs", level=Settings.LOG_LEVEL)
class HTMLAgentSystem:
"""
Main system that coordinates all agents for HTML analysis
"""
def __init__(self):
# Validate settings
try:
Settings.validate()
except ValueError as e:
logger.error(f"Configuration error: {e}")
raise
self.orchestrator = Orchestrator()
self.analyzer = AnalyzerAgent()
self.code_generator = CodeGeneratorAgent()
self.visual_analyzer = VisualAnalyzer()
self.code_validator = CodeValidatorAgent()
self.markdown_converter = MarkdownConverterAgent()
self.output_dir = Path(Settings.OUTPUT_DIR)
self.output_dir.mkdir(exist_ok=True)
self.checkpoint = CheckpointManager(self.output_dir)
def process_input(self, input_path: str, use_visual: bool = True, resume: bool = True) -> Dict[str, Any]:
"""
Process input - can be a directory or URL list file
"""
input_path_obj = Path(input_path)
# Note: Checkpoints are now managed per step, not globally
# Each step creates its own flow directory and checkpoint
# Check if it's a file (URL list) or directory
if input_path_obj.is_file():
logger.info(f"Processing URL list file: {input_path}")
return self._process_url_list(input_path, use_visual, resume)
elif input_path_obj.is_dir():
logger.info(f"Processing HTML directory: {input_path}")
return self._process_directory(input_path, use_visual, resume)
else:
logger.error(f"Input path does not exist: {input_path}")
return {"error": f"Input path does not exist: {input_path}"}
def _process_directory(self, html_directory: str, use_visual: bool = True, resume: bool = True) -> Dict[str, Any]:
"""
Process a directory of HTML files and generate extraction code
"""
# Step 1: Load HTML files
html_files = HTMLParser.load_html_files(html_directory)
if not html_files:
logger.error("No HTML files found in directory")
return {"error": "No HTML files found"}
logger.info(f"Found {len(html_files)} HTML files")
return self._process_html_files(html_files, use_visual, resume)
def _process_url_list(self, url_file: str, use_visual: bool = True, resume: bool = True) -> Dict[str, Any]:
"""
Process URLs from a file and generate extraction code
Note: This method should only be called when URL file is provided as custom input.
For typical/spread directories, HTML files should be pre-downloaded to their html/ directories.
"""
# This method is kept for backward compatibility with custom URL files
# In normal workflow, URLs should be pre-downloaded to input/html directories
logger.warning("Processing URL file directly. Consider pre-downloading HTML files to input directories.")
# Step 1: Load URLs
urls = URLDownloader.load_urls_from_file(url_file)
if not urls:
logger.error("No valid URLs found in file")
return {"error": "No valid URLs found"}
logger.info(f"Found {len(urls)} URLs")
# For custom URL files, download to a temporary directory in output
# (This is a fallback for custom inputs, not the normal workflow)
html_dir = self.output_dir / 'downloaded_html'
if resume and html_dir.exists() and any(html_dir.iterdir()):
logger.info("Using existing downloaded HTML files")
html_files = HTMLParser.load_html_files(str(html_dir))
if html_files:
# Add URL info if missing
for i, html_file in enumerate(html_files):
if 'url' not in html_file and i < len(urls):
html_file['url'] = urls[i]
else:
logger.info("Downloading HTML content from URLs...")
html_files = URLDownloader.download_multiple_urls(urls, output_dir=str(self.output_dir))
if not html_files:
logger.error("Failed to download any HTML content")
return {"error": "Failed to download HTML content"}
logger.info(f"Successfully downloaded {len(html_files)} HTML files")
return self._process_html_files(html_files, use_visual, resume)
def _execute_extraction_code(self, code_path: Path, output_dir: Path, json_schema: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
Execute the generated extraction code on spread directory
REQUIRED CODE INTERFACE SPECIFICATION:
======================================
The generated code MUST strictly follow this interface:
1. Class Definition:
- MUST define a class named 'HTMLExtractor'
- MUST have __init__ method with signature: __init__(self, schema: Dict[str, Any], logger: Optional[logging.Logger] = None)
- schema parameter MUST accept the JSON schema dictionary
2. Extract Method:
- MUST have a method named 'extract' (NOT extract_from_string, extract_from_file, etc.)
- Method signature MUST be: extract(self, html_content: Optional[str] = None, file_path: Optional[str] = None) -> Dict[str, Any]
- Parameter names MUST be exactly: 'html_content' and 'file_path' (no variations)
- Return type MUST be Dict[str, Any] (NOT ExtractionResult, NOT list, NOT other types)
- The method MUST return a plain dictionary with section names as keys
3. Input/Output:
- Input: html_content (str) OR file_path (str), at least one must be provided
- Output: Dict[str, Any] with extracted data, keys are section names from schema
4. Schema Constant (Optional but Recommended):
- MAY define SCHEMA constant at module level: SCHEMA: Dict[str, Any] = {...}
- If defined, should match the schema passed to __init__
Example interface:
```python
class HTMLExtractor:
def __init__(self, schema: Dict[str, Any], logger: Optional[logging.Logger] = None) -> None:
self.schema = schema
# ... initialization ...
def extract(self, html_content: Optional[str] = None, file_path: Optional[str] = None) -> Dict[str, Any]:
# Extract content and return Dict[str, Any]
return {"section1": value1, "section2": value2, ...}
```
"""
import importlib.util
import sys
from typing import Optional
# Check spread directory for HTML files or URLs
spread_html_dir = Settings.SPREAD_HTML_DIR
spread_urls_file = Settings.SPREAD_URLS_FILE
html_files_to_process = []
# Check if HTML files exist
if spread_html_dir.exists() and any(spread_html_dir.iterdir()):
# Load existing HTML files
html_files = HTMLParser.load_html_files(str(spread_html_dir))
html_files_to_process = html_files
logger.info(f"Found {len(html_files_to_process)} HTML files in spread/html directory")
elif spread_urls_file.exists():
# Download HTML files from URLs
logger.info(f"No HTML files in spread/html, downloading from {spread_urls_file}...")
logger.info(f"Using spread URLs file: {spread_urls_file}")
urls = URLDownloader.load_urls_from_file(str(spread_urls_file))
if not urls:
logger.warning(f"No valid URLs found in {spread_urls_file}")
return None
# Download to spread/html directory
spread_html_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Downloading {len(urls)} URLs to {spread_html_dir}...")
html_files = URLDownloader.download_multiple_urls(urls, output_dir=str(spread_html_dir))
if not html_files:
logger.warning("Failed to download HTML files from URLs")
return None
html_files_to_process = html_files
logger.info(f"Downloaded {len(html_files_to_process)} HTML files to spread/html")
else:
logger.warning("No HTML files or urls.txt found in spread directory")
return None
if not html_files_to_process:
logger.warning("No HTML files to process")
return None
# Load and execute the generated code
try:
# Load the extraction code module
spec = importlib.util.spec_from_file_location("extraction_code", code_path)
if spec is None or spec.loader is None:
raise ImportError(f"Failed to load extraction code from {code_path}")
extraction_module = importlib.util.module_from_spec(spec)
sys.modules['extraction_code'] = extraction_module
spec.loader.exec_module(extraction_module)
# Strictly follow the required interface
# 1. Must have HTMLExtractor class
if not hasattr(extraction_module, 'HTMLExtractor'):
raise ValueError("Generated code MUST define 'HTMLExtractor' class. Found classes: " +
str([name for name in dir(extraction_module) if isinstance(getattr(extraction_module, name, None), type)]))
# 2. Must have schema parameter in __init__
import inspect
init_signature = inspect.signature(extraction_module.HTMLExtractor.__init__)
init_params = list(init_signature.parameters.keys())
if 'schema' not in init_params:
raise ValueError(f"HTMLExtractor.__init__ MUST accept 'schema' parameter. Found parameters: {init_params}")
# 3. Get schema (prefer module SCHEMA constant, fallback to passed schema)
if hasattr(extraction_module, 'SCHEMA'):
schema_to_use = extraction_module.SCHEMA
else:
schema_to_use = json_schema
# 4. Instantiate extractor with schema
extractor = extraction_module.HTMLExtractor(schema=schema_to_use)
# 5. Must have extract method (exact name, not extract_from_string, etc.)
if not hasattr(extractor, 'extract'):
available_methods = [name for name in dir(extractor) if not name.startswith('_') and callable(getattr(extractor, name))]
raise ValueError(f"HTMLExtractor MUST have 'extract' method. Found methods: {available_methods}")
# 6. Verify extract method signature
extract_method = getattr(extractor, 'extract')
extract_sig = inspect.signature(extract_method)
extract_params = list(extract_sig.parameters.keys())
# Must have html_content or file_path parameter
if 'html_content' not in extract_params and 'file_path' not in extract_params:
raise ValueError(f"extract() method MUST accept 'html_content' or 'file_path' parameter. Found parameters: {extract_params}")
# Must return Dict[str, Any]
if extract_sig.return_annotation == inspect.Signature.empty:
raise ValueError("extract() method MUST have return type annotation: -> Dict[str, Any]")
return_type_str = str(extract_sig.return_annotation)
if 'Dict' not in return_type_str and 'dict' not in return_type_str.lower():
raise ValueError(f"extract() method MUST return Dict[str, Any]. Found return type: {return_type_str}")
extract_func = extract_method
# Create results directory for extraction results
results_dir = output_dir / 'extraction_results'
results_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Created results directory: {results_dir}")
# Process each HTML file and save individual JSON files
results_summary = []
processed_count = 0
failed_count = 0
for html_file in html_files_to_process:
html_content = html_file.get('content', '')
file_path = html_file.get('path', '')
file_name = html_file.get('name', 'unknown')
if not html_content and file_path:
# Try to read from file
try:
with open(file_path, 'r', encoding='utf-8') as f:
html_content = f.read()
except Exception as e:
logger.warning(f"Failed to read {file_path}: {e}")
failed_count += 1
results_summary.append({
'file': file_name,
'path': file_path,
'status': 'failed',
'error': f"Failed to read file: {str(e)}"
})
continue
if not html_content:
logger.warning(f"No HTML content for {file_name}")
failed_count += 1
results_summary.append({
'file': file_name,
'path': file_path,
'status': 'failed',
'error': 'No HTML content available'
})
continue
try:
# Extract content using the generated code
# Strictly follow the interface: extract(html_content=..., file_path=...)
if html_content:
result = extractor.extract(html_content=html_content)
elif file_path:
result = extractor.extract(file_path=file_path)
else:
raise ValueError("Either html_content or file_path must be provided")
# Result must be Dict[str, Any]
if not isinstance(result, dict):
raise TypeError(f"extract() method MUST return Dict[str, Any], got {type(result)}")
# Generate JSON filename from HTML filename
# Remove .html extension and add .json
json_filename = file_name.rsplit('.html', 1)[0] if file_name.endswith('.html') else file_name
json_filename = json_filename.rsplit('.htm', 1)[0] if json_filename.endswith('.htm') else json_filename
json_filename = f"{json_filename}.json"
# Clean filename to remove invalid characters
import re
json_filename = re.sub(r'[^\w\-_\.]', '_', json_filename)
# Save individual result JSON file to results directory
individual_result_path = results_dir / json_filename
with open(individual_result_path, 'w', encoding='utf-8') as f:
json.dump(result, f, indent=2, ensure_ascii=False)
logger.info(f"Successfully extracted and saved result for {file_name} to extraction_results/{json_filename}")
processed_count += 1
results_summary.append({
'file': file_name,
'path': file_path,
'status': 'success',
'result_file': json_filename
})
except Exception as e:
logger.error(f"Failed to extract content from {file_name}: {e}")
failed_count += 1
results_summary.append({
'file': file_name,
'path': file_path,
'status': 'failed',
'error': str(e)
})
# Save summary file with all results (in flow5 directory, not in results folder)
summary_path = output_dir / 'extraction_results_summary.json'
with open(summary_path, 'w', encoding='utf-8') as f:
json.dump({
'total_files': len(html_files_to_process),
'processed_files': processed_count,
'failed_files': failed_count,
'results_directory': 'extraction_results',
'results': results_summary
}, f, indent=2, ensure_ascii=False)
logger.info(f"Extraction summary saved to {summary_path}")
logger.info(f"Generated {processed_count} individual result JSON files in extraction_results/ directory")
return {
'processed_count': processed_count,
'failed_count': failed_count,
'results_directory': str(results_dir),
'summary_path': str(summary_path),
'individual_files': processed_count
}
except Exception as e:
logger.error(f"Failed to execute extraction code: {e}")
import traceback
logger.error(traceback.format_exc())
return None
def _fix_markdown_converter_syntax(self, code: str, syntax_error: SyntaxError) -> str:
"""
Attempt to fix common syntax errors in generated markdown converter code
"""
import re
lines = code.split('\n')
error_line_num = syntax_error.lineno - 1 if syntax_error.lineno and syntax_error.lineno <= len(lines) else len(lines) - 1
if error_line_num < len(lines):
error_line = lines[error_line_num]
# Fix unterminated f-strings
if 'f"' in error_line or "f'" in error_line or 'f"""' in error_line or "f'''" in error_line:
# Check for triple-quoted f-strings first
if 'f"""' in error_line:
# Find the start of the f-string
f_start = error_line.find('f"""')
if f_start != -1:
# Check if it's closed on the same line
remaining = error_line[f_start + 4:]
if '"""' not in remaining:
# Not closed, need to find where it should end
# Look ahead for closing triple quotes
found_close = False
for i in range(error_line_num + 1, min(error_line_num + 20, len(lines))):
if '"""' in lines[i]:
found_close = True
break
if not found_close:
# Add closing triple quotes at end of current line or next logical place
# If line ends with newline escape, it's probably a multi-line string
if error_line.rstrip().endswith('\\n') or error_line.rstrip().endswith('\\'):
# Convert to proper multi-line f-string or add closing
# Try to find a good place to close it
if error_line_num + 1 < len(lines):
next_line = lines[error_line_num + 1]
# If next line is part of the string content, we need to close after it
if next_line.strip() and not next_line.strip().startswith('"""'):
# Look for where the string should end
# Common pattern: f"""\n{content}\n"""
# Find the next non-indented line or closing pattern
for i in range(error_line_num + 1, min(error_line_num + 10, len(lines))):
if lines[i].strip() and not lines[i].startswith(' ') and not lines[i].startswith('\t'):
# Found next statement, close before it
lines[i-1] = lines[i-1].rstrip() + '"""'
break
else:
# No clear end, close at end of next line
if error_line_num + 1 < len(lines):
lines[error_line_num + 1] = lines[error_line_num + 1].rstrip() + '"""'
else:
lines[error_line_num] = error_line.rstrip() + '"""'
else:
# Already has closing, might be a different issue
pass
else:
lines[error_line_num] = error_line.rstrip() + '"""'
else:
# Simple case, just add closing
lines[error_line_num] = error_line.rstrip() + '"""'
elif "f'''" in error_line:
# Similar logic for triple single quotes
f_start = error_line.find("f'''")
if f_start != -1:
remaining = error_line[f_start + 4:]
if "'''" not in remaining:
found_close = False
for i in range(error_line_num + 1, min(error_line_num + 20, len(lines))):
if "'''" in lines[i]:
found_close = True
break
if not found_close:
if error_line.rstrip().endswith('\\n') or error_line.rstrip().endswith('\\'):
if error_line_num + 1 < len(lines):
next_line = lines[error_line_num + 1]
if next_line.strip() and not next_line.strip().startswith("'''"):
for i in range(error_line_num + 1, min(error_line_num + 10, len(lines))):
if lines[i].strip() and not lines[i].startswith(' ') and not lines[i].startswith('\t'):
lines[i-1] = lines[i-1].rstrip() + "'''"
break
else:
if error_line_num + 1 < len(lines):
lines[error_line_num + 1] = lines[error_line_num + 1].rstrip() + "'''"
else:
lines[error_line_num] = error_line.rstrip() + "'''"
else:
lines[error_line_num] = error_line.rstrip() + "'''"
else:
lines[error_line_num] = error_line.rstrip() + "'''"
# Fix regular f-strings (f" or f')
elif 'f"' in error_line or "f'" in error_line:
# Check if f-string is not properly closed
f_string_pattern = r'f["\']'
matches = list(re.finditer(f_string_pattern, error_line))
if matches:
last_match = matches[-1]
quote_char = error_line[last_match.end() - 1]
remaining = error_line[last_match.end():]
# Count quotes in remaining part
quote_count = remaining.count(quote_char)
# Count escaped quotes
escaped_quotes = remaining.count('\\' + quote_char)
# Actual unescaped quotes
unescaped_quotes = quote_count - escaped_quotes
# If odd number of unescaped quotes, string is not closed
if unescaped_quotes % 2 == 0: # Even means not closed (opening quote not counted)
# Check if line ends without closing quote
if not error_line.rstrip().endswith(quote_char):
# Check if next line might be continuation
if error_line_num + 1 < len(lines):
next_line = lines[error_line_num + 1]
# If next line is indented and has content, might be part of the string
if next_line.strip() and (next_line.startswith(' ') or next_line.startswith('\t')):
# This is likely a multi-line string that should use triple quotes
# Convert to triple-quoted f-string
# Find the opening f"
f_pos = error_line.find('f"')
if f_pos != -1:
# Replace f" with f""" and find where to close
lines[error_line_num] = error_line[:f_pos+1] + '"""' + error_line[f_pos+2:]
# Find where to close (next non-indented line or end of block)
for i in range(error_line_num + 1, min(error_line_num + 15, len(lines))):
if lines[i].strip() and not (lines[i].startswith(' ') or lines[i].startswith('\t')):
# Found next statement, close before it
lines[i-1] = lines[i-1].rstrip() + '"""'
break
else:
# No clear end, close at end of next line
if error_line_num + 1 < len(lines):
lines[error_line_num + 1] = lines[error_line_num + 1].rstrip() + '"""'
else:
# Add closing quote
lines[error_line_num] = error_line.rstrip() + quote_char
else:
# Add closing quote at end
lines[error_line_num] = error_line.rstrip() + quote_char
fixed_code = '\n'.join(lines)
# Additional fixes for common issues
# Fix incomplete triple-quoted strings in f-strings (more aggressive)
# Look for patterns like f"""\n without closing
fixed_code = re.sub(r'(f"""[^"]*?)(\n)(?![^"]*""")', r'\1\2"""', fixed_code, flags=re.MULTILINE | re.DOTALL)
fixed_code = re.sub(r"(f'''[^']*?)(\n)(?![^']*''')", r"\1\2'''", fixed_code, flags=re.MULTILINE | re.DOTALL)
return fixed_code
def _execute_markdown_conversion(self, converter_code_path: Path, json_results_dir: Path, output_dir: Path) -> Optional[Dict[str, Any]]:
"""
Execute the markdown converter code on JSON results
"""
import importlib.util
import sys
if not converter_code_path.exists():
logger.error(f"Markdown converter code not found: {converter_code_path}")
return None
if not json_results_dir.exists():
logger.error(f"JSON results directory not found: {json_results_dir}")
return None
# Load all JSON files
json_files = list(json_results_dir.glob('*.json'))
if not json_files:
logger.warning("No JSON files found to convert")
return None
# Load and execute the converter code
try:
# Load the converter code module
spec = importlib.util.spec_from_file_location("markdown_converter", converter_code_path)
if spec is None or spec.loader is None:
raise ImportError(f"Failed to load markdown converter code from {converter_code_path}")
converter_module = importlib.util.module_from_spec(spec)
sys.modules['markdown_converter'] = converter_module
spec.loader.exec_module(converter_module)
# Strictly follow the required interface
# 1. Must have MarkdownConverter class
if not hasattr(converter_module, 'MarkdownConverter'):
raise ValueError("Generated code MUST define 'MarkdownConverter' class. Found classes: " +
str([name for name in dir(converter_module) if isinstance(getattr(converter_module, name, None), type)]))
# 2. Verify __init__ signature (should have no required parameters)
import inspect
init_signature = inspect.signature(converter_module.MarkdownConverter.__init__)
init_params = [p for p in init_signature.parameters.keys() if p != 'self']
if init_params:
# Check if all params have defaults
for param_name in init_params:
param = init_signature.parameters[param_name]
if param.default == inspect.Parameter.empty:
raise ValueError(f"MarkdownConverter.__init__() MUST have no required parameters. Found: {init_params}")
# 3. Instantiate converter
converter = converter_module.MarkdownConverter()
# 4. Must have convert method (exact name)
if not hasattr(converter, 'convert'):
available_methods = [name for name in dir(converter) if not name.startswith('_') and callable(getattr(converter, name))]
raise ValueError(f"MarkdownConverter MUST have 'convert' method. Found methods: {available_methods}")
# 5. Verify convert method signature
convert_method = getattr(converter, 'convert')
convert_sig = inspect.signature(convert_method)
convert_params = list(convert_sig.parameters.keys())
# Must have json_data parameter
if 'json_data' not in convert_params:
raise ValueError(f"convert() method MUST accept 'json_data' parameter. Found parameters: {convert_params}")
# Must return str
if convert_sig.return_annotation == inspect.Signature.empty:
raise ValueError("convert() method MUST have return type annotation: -> str")
return_type_str = str(convert_sig.return_annotation)
if 'str' not in return_type_str.lower() or 'str' != return_type_str.strip():
# Allow Optional[str] or Union[str, ...] but must include str
if 'str' not in return_type_str:
raise ValueError(f"convert() method MUST return str. Found return type: {return_type_str}")
# Create markdown output directory
markdown_output_dir = output_dir / 'markdown_output'
markdown_output_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Created markdown output directory: {markdown_output_dir}")
# Process each JSON file
processed_count = 0
failed_count = 0
results_summary = []
for json_file in json_files:
try:
# Load JSON
with open(json_file, 'r', encoding='utf-8') as f:
json_data = json.load(f)
# Convert to Markdown
# Strictly follow the interface: convert(json_data=...)
markdown_content = converter.convert(json_data=json_data)
# Result must be str
if not isinstance(markdown_content, str):
raise TypeError(f"convert() method MUST return str, got {type(markdown_content)}")
# Generate markdown filename
markdown_filename = json_file.stem + '.md'
markdown_path = markdown_output_dir / markdown_filename
# Save Markdown file
with open(markdown_path, 'w', encoding='utf-8') as f:
f.write(markdown_content)
logger.info(f"Successfully converted {json_file.name} to {markdown_filename}")
processed_count += 1
results_summary.append({
'json_file': json_file.name,
'markdown_file': markdown_filename,
'status': 'success'
})
except Exception as e:
logger.error(f"Failed to convert {json_file.name}: {e}")
failed_count += 1
results_summary.append({
'json_file': json_file.name,
'status': 'failed',
'error': str(e)
})
# Save summary
summary_path = output_dir / 'markdown_conversion_summary.json'
with open(summary_path, 'w', encoding='utf-8') as f:
json.dump({
'total_files': len(json_files),
'processed_files': processed_count,
'failed_files': failed_count,
'markdown_output_directory': 'markdown_output',
'results': results_summary
}, f, indent=2, ensure_ascii=False)
logger.info(f"Markdown conversion summary saved to {summary_path}")
logger.info(f"Generated {processed_count} Markdown files in markdown_output/ directory")
return {
'processed_count': processed_count,
'failed_count': failed_count,
'markdown_output_directory': str(markdown_output_dir),
'summary_path': str(summary_path)
}
except Exception as e:
logger.error(f"Failed to execute markdown conversion: {e}")
import traceback
logger.error(traceback.format_exc())
return None
def _process_html_files(self, html_files: List[Dict[str, str]], use_visual: bool = True, resume: bool = True) -> Dict[str, Any]:
"""
Process HTML files and generate extraction code with checkpoint support
Each step creates a new flow directory
"""
file_identifiers = [f.get('url', f.get('path', 'unknown')) for f in html_files]
# Initialize variables
analysis_results = None
visual_results = None
synthesized = None
json_schema = None
extraction_code = None
# Load checkpoints from existing flow directories if resume is enabled
# Track which steps have been completed based on checkpoints
completed_steps = {}
if resume:
# Find all existing flow directories and load checkpoints
existing_flows = []
if Settings.OUTPUT_DIR.exists():
for item in Settings.OUTPUT_DIR.iterdir():
if item.is_dir() and item.name.startswith('flow'):
try:
flow_num = int(item.name[4:])
checkpoint_manager = CheckpointManager(item)
checkpoint = checkpoint_manager.load_checkpoint()
if checkpoint:
step = checkpoint.get('step', 'unknown')
existing_flows.append({
'flow_id': flow_num,
'flow_dir': item,
'checkpoint': checkpoint,
'step': step
})
# Map step to flow_id for later use
if step == "text_analysis":
completed_steps['step1'] = flow_num
elif step == "visual_analysis":
completed_steps['step2'] = flow_num
elif step == "synthesized":
completed_steps['step3'] = flow_num
elif step == "schema":
completed_steps['step4'] = flow_num
elif step == "code":
completed_steps['step5'] = flow_num
except (ValueError, Exception) as e:
logger.debug(f"Could not load checkpoint from {item.name}: {e}")
continue
# Sort by flow_id to process in order
existing_flows.sort(key=lambda x: x['flow_id'])
# Load data from checkpoints in order (later checkpoints contain all previous data)
for flow_info in existing_flows:
checkpoint = flow_info['checkpoint']
step = checkpoint.get('step')
data = checkpoint.get('data', {})
logger.info(f"Found checkpoint in {flow_info['flow_dir'].name}: step={step}")
# Load data based on step (later steps contain all previous data)
if step == "text_analysis":
analysis_results = data.get('analysis_results')
logger.info(f"Loaded text analysis results from {flow_info['flow_dir'].name}")
elif step == "visual_analysis":
visual_results = data.get('visual_results')
analysis_results = data.get('analysis_results') # Also load previous step data
logger.info(f"Loaded visual analysis results from {flow_info['flow_dir'].name}")
elif step == "synthesized":
synthesized = data.get('synthesized')
analysis_results = data.get('analysis_results')
visual_results = data.get('visual_results')
logger.info(f"Loaded synthesized results from {flow_info['flow_dir'].name}")
elif step == "schema":
json_schema = data.get('schema')
synthesized = data.get('synthesized')
analysis_results = data.get('analysis_results')
visual_results = data.get('visual_results')
logger.info(f"Loaded schema from {flow_info['flow_dir'].name}")
elif step == "code_generated":
extraction_code = data.get('code')
json_schema = data.get('schema')
synthesized = data.get('synthesized')
analysis_results = data.get('analysis_results')
visual_results = data.get('visual_results')
logger.info(f"Loaded generated code from {flow_info['flow_dir'].name}")
elif step == "code_validated" or step == "code":
extraction_code = data.get('code')
validation_result = data.get('validation')
json_schema = data.get('schema')
synthesized = data.get('synthesized')
analysis_results = data.get('analysis_results')
visual_results = data.get('visual_results')
logger.info(f"Loaded validated code from {flow_info['flow_dir'].name}")
if existing_flows:
logger.info(f"Resuming from checkpoints: found {len(existing_flows)} completed steps")
logger.info(f"Completed steps: {list(completed_steps.keys())}")
# Step 1: Analyze HTML files with analyzer agent
# Check if we already have results from checkpoint
if analysis_results is not None:
logger.info("Step 1: Using text analysis results from checkpoint, skipping...")
# Use existing flow directory from checkpoint
step1_flow_id = completed_steps.get('step1', 1)
step1_output_dir = Settings.get_flow_output_dir(step1_flow_id)
step1_checkpoint = CheckpointManager(step1_output_dir)
else:
# Create new flow directory for this step
step1_flow_id = Settings.get_next_flow_id()
step1_output_dir = Settings.get_flow_output_dir(step1_flow_id)
step1_checkpoint = CheckpointManager(step1_output_dir)
# Check if step result exists, if yes, skip and load from file
if step1_checkpoint.step_result_exists("step1_text_analysis"):
logger.info("Step 1: Using cached text analysis results (file exists)")
analysis_results = step1_checkpoint.load_step_result("step1_text_analysis")
# Also load from checkpoint if available
checkpoint = step1_checkpoint.load_checkpoint()
if checkpoint and checkpoint.get('step') == 'text_analysis':
analysis_results = checkpoint.get('data', {}).get('analysis_results', analysis_results)
else:
logger.info("Step 1: Analyzing HTML structures with Analyzer Agent...")
analysis_results = []
for html_file in html_files:
file_identifier = html_file.get('url', html_file.get('path', 'unknown'))
result = self.analyzer.analyze_html_structure(
html_file['content'],
file_identifier
)
analysis_results.append(result)
# Save step result to step1 flow directory
step1_checkpoint.save_step_result("step1_text_analysis", analysis_results)
step1_checkpoint.save_checkpoint("text_analysis", {
"analysis_results": analysis_results,
"file_identifiers": file_identifiers
})
logger.info(f"Step 1 results saved to flow{step1_flow_id}")
# Step 2: Visual analysis (optional)
if use_visual:
# Check if we already have results from checkpoint
if visual_results is not None:
logger.info("Step 2: Using visual analysis results from checkpoint, skipping...")
# Use existing flow directory from checkpoint
step2_flow_id = completed_steps.get('step2', 2)
step2_output_dir = Settings.get_flow_output_dir(step2_flow_id)
step2_checkpoint = CheckpointManager(step2_output_dir)
else:
# Create new flow directory for this step
step2_flow_id = Settings.get_next_flow_id()
step2_output_dir = Settings.get_flow_output_dir(step2_flow_id)
step2_checkpoint = CheckpointManager(step2_output_dir)
# Check if step result exists, if yes, skip and load from file
if step2_checkpoint.step_result_exists("step2_visual_analysis"):
logger.info("Step 2: Using cached visual analysis results (file exists)")
visual_results = step2_checkpoint.load_step_result("step2_visual_analysis")
# Also load from checkpoint if available
checkpoint = step2_checkpoint.load_checkpoint()
if checkpoint and checkpoint.get('step') == 'visual_analysis':
visual_results = checkpoint.get('data', {}).get('visual_results', visual_results)
analysis_results = checkpoint.get('data', {}).get('analysis_results', analysis_results)
else:
logger.info("Step 2: Performing visual analysis...")
visual_results = []
for html_file in html_files:
file_identifier = html_file.get('url', html_file.get('path', 'unknown'))
visual_result = self.visual_analyzer.analyze_html_visually(
html_file['content'],
file_identifier
)
visual_results.append(visual_result)
# Save step result to step2 flow directory
step2_checkpoint.save_step_result("step2_visual_analysis", visual_results)
step2_checkpoint.save_checkpoint("visual_analysis", {
"analysis_results": analysis_results,
"visual_results": visual_results,
"file_identifiers": file_identifiers
})
logger.info(f"Step 2 results saved to flow{step2_flow_id}")
else:
visual_results = []
# Step 3: Orchestrator synthesizes results
# Check if we already have results from checkpoint
if synthesized is not None:
logger.info("Step 3: Using synthesized results from checkpoint, skipping...")
# Use existing flow directory from checkpoint
step3_flow_id = completed_steps.get('step3', 3)
step3_output_dir = Settings.get_flow_output_dir(step3_flow_id)
step3_checkpoint = CheckpointManager(step3_output_dir)
else:
# Create new flow directory for this step
step3_flow_id = Settings.get_next_flow_id()
step3_output_dir = Settings.get_flow_output_dir(step3_flow_id)
step3_checkpoint = CheckpointManager(step3_output_dir)
# Check if step result exists, if yes, skip and load from file
if step3_checkpoint.step_result_exists("step3_synthesized"):
logger.info("Step 3: Using cached synthesized results (file exists)")
synthesized = step3_checkpoint.load_step_result("step3_synthesized")
# Also load from checkpoint if available
checkpoint = step3_checkpoint.load_checkpoint()
if checkpoint and checkpoint.get('step') == 'synthesized':
synthesized = checkpoint.get('data', {}).get('synthesized', synthesized)
analysis_results = checkpoint.get('data', {}).get('analysis_results', analysis_results)
visual_results = checkpoint.get('data', {}).get('visual_results', visual_results)
else:
logger.info("Step 3: Orchestrator synthesizing analysis results...")
combined_results = {
"text_analysis": analysis_results,
"visual_analysis": visual_results if use_visual else []
}
synthesized = self.orchestrator.coordinate_analysis(file_identifiers, combined_results)
# Save step result to step3 flow directory
step3_checkpoint.save_step_result("step3_synthesized", synthesized)
step3_checkpoint.save_checkpoint("synthesized", {
"analysis_results": analysis_results,
"visual_results": visual_results if use_visual else [],
"synthesized": synthesized,
"file_identifiers": file_identifiers
})
logger.info(f"Step 3 results saved to flow{step3_flow_id}")
# Step 4: Generate final JSON schema
# Check if we already have results from checkpoint
if json_schema is not None:
logger.info("Step 4: Using schema from checkpoint, skipping...")
# Use existing flow directory from checkpoint
step4_flow_id = completed_steps.get('step4', 4)
step4_output_dir = Settings.get_flow_output_dir(step4_flow_id)
step4_checkpoint = CheckpointManager(step4_output_dir)
schema_path = step4_output_dir / 'extraction_schema.json'
else:
# Create new flow directory for this step
step4_flow_id = Settings.get_next_flow_id()
step4_output_dir = Settings.get_flow_output_dir(step4_flow_id)
step4_checkpoint = CheckpointManager(step4_output_dir)
# Check if step result exists, if yes, skip and load from file
schema_path = step4_output_dir / 'extraction_schema.json'
if step4_checkpoint.step_result_exists("step4_schema") or schema_path.exists():
logger.info("Step 4: Using cached schema (file exists)")
json_schema = step4_checkpoint.load_step_result("step4_schema")
if json_schema is None and schema_path.exists():
with open(schema_path, 'r', encoding='utf-8') as f:
json_schema = json.load(f)
# Also load from checkpoint if available
checkpoint = step4_checkpoint.load_checkpoint()
if checkpoint and checkpoint.get('step') == 'schema':
json_schema = checkpoint.get('data', {}).get('schema', json_schema)
synthesized = checkpoint.get('data', {}).get('synthesized', synthesized)
analysis_results = checkpoint.get('data', {}).get('analysis_results', analysis_results)
visual_results = checkpoint.get('data', {}).get('visual_results', visual_results)
else:
logger.info("Step 4: Generating final JSON schema...")
json_schema = self.orchestrator.generate_final_schema(synthesized)
# Save schema to step4 flow directory
with open(schema_path, 'w', encoding='utf-8') as f:
json.dump(json_schema, f, indent=2, ensure_ascii=False)
logger.info(f"Schema saved to {schema_path}")
# Save step result to step4 flow directory
step4_checkpoint.save_step_result("step4_schema", json_schema)
step4_checkpoint.save_checkpoint("schema", {
"analysis_results": analysis_results,
"visual_results": visual_results if use_visual else [],
"synthesized": synthesized,
"schema": json_schema,
"file_identifiers": file_identifiers
})
logger.info(f"Step 4 results saved to flow{step4_flow_id}")
# Step 5: Generate extraction code
# Check if we already have code from checkpoint
if extraction_code is not None:
logger.info("Step 5: Using extraction code from checkpoint, skipping generation...")
# Use existing flow directory from checkpoint
step5_flow_id = completed_steps.get('step5', 5)
step5_output_dir = Settings.get_flow_output_dir(step5_flow_id)
step5_checkpoint = CheckpointManager(step5_output_dir)
code_path = step5_output_dir / 'extraction_code.py'
# Load code from file if exists
if code_path.exists():
with open(code_path, 'r', encoding='utf-8') as f:
extraction_code = f.read()
else:
# Check for existing incomplete flow5 directory first
# Look for flow directories with step="schema" (indicating Step 5 failed)
existing_flow5_id = None
if Settings.OUTPUT_DIR.exists():
for item in Settings.OUTPUT_DIR.iterdir():
if item.is_dir() and item.name.startswith('flow'):
try:
flow_num = int(item.name[4:])
# Check if this is a flow5 directory (or any flow with schema checkpoint but no code)
checkpoint_manager = CheckpointManager(item)
checkpoint = checkpoint_manager.load_checkpoint()
if checkpoint:
checkpoint_step = checkpoint.get('step')
# If checkpoint is "schema" and has code_generation_failed, reuse this flow
if checkpoint_step == "schema" and checkpoint.get('data', {}).get('code_generation_failed'):
# This is an incomplete Step 5, reuse it
existing_flow5_id = flow_num
logger.info(f"Found incomplete Step 5 in {item.name}, will reuse it")
break
except (ValueError, Exception):
continue