def extract_title(doc):
for para in doc.paragraphs:
if para.text.strip():
return para.text.strip()
return "Blank or No Title"
Extract summary
def extract_file_summary(doc, max_lines=5):
lines = []
for para in doc.paragraphs:
line = para.text.strip()
if line:
lines.append(line)
if len(lines) >= max_lines:
break
return " ".join(lines) if lines else "No content in document."
Extract present/missing schema-based sections
def analyze_structure(doc):
section_map = {key: False for key in expected_sections_with_titles}
for para in doc.paragraphs:
text = para.text.strip().upper()
for section in section_map:
if section in text:
section_map[section] = True
present = [f"{k} {expected_sections_with_titles[k]}" for k, v in section_map.items() if v]
missing = [f"{k} {expected_sections_with_titles[k]}" for k, v in section_map.items() if not v]
return present, missing
def extract_unexpected_headings(doc):
unexpected = []
for para in doc.paragraphs:
line = para.text.strip()
if not line:
continue
if (line.upper().startswith("PART-") or line.isupper()):
section_key = line.split()[0].upper()
if section_key not in expected_sections_with_titles:
unexpected.append(line)
return list(set(unexpected))
Process a single file
def process_file(file_path):
try:
doc = Document(file_path)
if not doc.paragraphs or all(not p.text.strip() for p in doc.paragraphs):
return "Blank or No Title", [], [], "Blank file.", []
title = extract_title(doc)
present, missing = analyze_structure(doc)
summary = extract_file_summary(doc)
unexpected = extract_unexpected_headings(doc)
return title, present, missing, summary, unexpected
except Exception as e:
return f"Error: {str(e)}", [], [], f"Error occurred: {str(e)}", []
def extract_title(doc):
for para in doc.paragraphs:
if para.text.strip():
return para.text.strip()
return "Blank or No Title"
Extract brief summary (first few non-empty lines)
def extract_file_summary(doc, max_lines=5):
lines = []
for para in doc.paragraphs:
line = para.text.strip()
if line:
lines.append(line)
if len(lines) >= max_lines:
break
return " ".join(lines) if lines else "No content in document."
Use regex to analyze which schema sections are present
def analyze_structure(doc):
section_map = {key: False for key in expected_sections_with_titles}
for para in doc.paragraphs:
text = para.text.strip()
for key, pattern in section_patterns.items():
if pattern.search(text):
section_map[key] = True
present = [f"{k} {expected_sections_with_titles[k]}" for k, v in section_map.items() if v]
missing = [f"{k} {expected_sections_with_titles[k]}" for k, v in section_map.items() if not v]
return present, missing
Detect headings not in schema, using uppercase or 'PART' keywords
def extract_unexpected_headings(doc):
unexpected = []
for para in doc.paragraphs:
line = para.text.strip()
if not line:
continue
if re.match(r"PART[- ]?[A-Z0-9()]+", line.upper()) or line.isupper():
matched = any(pattern.search(line) for pattern in section_patterns.values())
if not matched:
unexpected.append(line)
return list(set(unexpected))
Process one Word document
def process_file(file_path):
try:
doc = Document(file_path)
if not doc.paragraphs or all(not p.text.strip() for p in doc.paragraphs):
return "Blank or No Title", [], [], "Blank file.", []
title = extract_title(doc)
present, missing = analyze_structure(doc)
summary = extract_file_summary(doc)
unexpected = extract_unexpected_headings(doc)
return title, present, missing, summary, unexpected
except Exception as e:
return f"Error: {str(e)}", [], [], f"Error occurred: {str(e)}", []
can you tell the main diffference between these option#1 and option#2 and pipeline structure,which is best method for useful for 2.5k files
Assistant
Both Option #1 and Option #2 are Python scripts designed to process Word documents, analyze their structure, and generate an Excel report. They share a similar pipeline but differ in their approach to section detection and robustness. Below, I’ll outline the main differences, analyze the pipeline structure, and recommend the best method for processing 2,500 files.
Main Differences Between Option #1 and Option #2
Section Detection Mechanism:
Option #1:
Uses simple string matching (section in text) to detect schema-based sections.
This approach is case-sensitive and rigid, meaning it might miss sections if there are slight variations in formatting (e.g., extra spaces, different separators like hyphens or parentheses).
Example: If a document has PART II instead of PART-II, it might not detect it.
Option #2:
Uses regular expressions (re.compile) to detect sections, making it more flexible and robust.
The regex patterns account for variations in formatting (e.g., PART-II, PART II, PARTII, etc.) by making separators like hyphens and parentheses optional and case-insensitive.
Example: It can detect PART-II, PART II, or PARTII as the same section, improving accuracy.
Unexpected Headings Detection:
Option #1:
Uses a simpler approach to detect unexpected headings by checking if a line starts with PART- or is entirely uppercase.
This method might miss nuanced cases or produce false positives (e.g., detecting a random uppercase line as a heading).
Option #2:
Uses a more refined approach with regex to detect unexpected headings (e.g., PART[- ]?[A-Z0-9()]+) and cross-checks against the expected schema sections.
This reduces false positives and improves the accuracy of identifying non-schema headings.
Code Readability and Maintainability:
Option #1:
The code is straightforward but less modular and harder to maintain or extend.
It lacks comments or explanations, making it less developer-friendly.
The code is better organized, with comments and clear variable names.
It uses a dictionary of precompiled regex patterns (section_patterns), which is more efficient for repeated use and easier to extend (e.g., adding new sections).
Robustness:
Option #1:
Less robust due to its rigid string matching. It might fail to detect sections in documents with inconsistent formatting.
Option #2:
More robust due to its use of regex, which handles variations in document formatting better.
Performance:
Option #1:
Slightly faster for small datasets because it uses simple string matching, which is computationally cheaper than regex.
Option #2:
Slightly slower due to regex operations, but the difference is negligible for most use cases, especially when precompiling regex patterns (as done in Option #2).
Pipeline Structure (Common to Both Options)
Both scripts follow a similar pipeline for processing files and generating the Excel report. Here’s the breakdown of the pipeline:
Input Handling:
Step: Read all folders and files in the base directory (base_folder).
Details: Filters for .doc and .docx files, ignoring temporary files (e.g., ~$ files).
File Conversion:
Step: Convert .doc files to .docx using the win32com library (MS Word COM API).
Details: Temporary .docx files are created and deleted after processing.
Document Processing:
Step: Open each .docx file using the python-docx library and extract relevant information.
Details:
Extract the title (first non-empty line).
Extract a summary (first few non-empty lines).
Analyze the document structure to identify present and missing schema sections.
Details: Errors are logged in the output (e.g., "Error: ...").
Data Aggregation:
Step: Collect results for each file into a list of dictionaries.
Details: Each dictionary contains metadata (folder name, file name, file count) and analysis results (title, sections present/missing, summary, unexpected headings).
Output Generation:
Step: Convert the results into a pandas DataFrame and save it as an Excel file.
Details: The Excel file is saved to the specified output_file path, with columns for folder/file metadata and analysis results.
Which is Best for Processing 2,500 Files?
For processing 2,500 files, the key considerations are accuracy, robustness, performance, and maintainability. Here’s the recommendation:
Best Method: Option #2
Reasons:
Accuracy and Robustness:
Option #2’s use of regex makes it far more accurate and robust, especially when dealing with real-world documents that may have inconsistent formatting (e.g., extra spaces, missing hyphens, varying capitalization).
For 2,500 files, you’re likely to encounter such variations, and Option #1’s rigid string matching could miss sections or produce incorrect results.
Performance:
While Option #2 is slightly slower due to regex, the difference is negligible for 2,500 files, especially since the regex patterns are precompiled (compiled once and reused).
The bottleneck in processing 2,500 files will likely be I/O operations (reading files, converting .doc to .docx, writing to Excel) rather than section detection.
Maintainability:
Option #2 is better documented and structured, making it easier to debug, extend, or modify in the future (e.g., adding new schema sections or changing the output format).
For a large-scale task like processing 2,500 files, maintainability is crucial, especially if issues arise or requirements change.
Error Handling:
Both options handle errors similarly, but Option #2’s clearer structure makes it easier to add more detailed error logging or recovery mechanisms if needed.
When to Use Option #1?
Option #1 might be preferable only if:
You are certain that all 2,500 files have perfectly consistent formatting (e.g., exact section names like PART-II with no variations).
Performance is a critical concern, and you’re willing to sacrifice accuracy for a slight speed gain (though this is unlikely to be significant for 2,500 files).
Recommendations for Processing 2,500 Files
To ensure smooth and efficient processing of 2,500 files, consider the following enhancements (applicable to Option #2):
Parallel Processing:
Processing 2,500 files sequentially can be time-consuming, especially due to I/O operations and .doc to .docx conversions.
Use Python’s multiprocessing or concurrent.futures to process files in parallel, leveraging multiple CPU cores.
Example: Use concurrent.futures.ThreadPoolExecutor for I/O-bound tasks (file reading/writing) or ProcessPoolExecutor for CPU-bound tasks (regex matching).
Batch Processing:
Instead of saving all results to a single Excel file at the end, consider saving intermediate results (e.g., after every 500 files) to avoid data loss in case of crashes.
Use pandas to append to an existing Excel file or save results in chunks.
Error Logging:
Enhance error logging by writing detailed logs to a separate file (e.g., using the logging module). This will help diagnose issues with specific files.
Add timing information to track how long each step (conversion, processing, saving) takes. This can help identify bottlenecks.
Example: Use the time module to measure execution time for each file or batch.
File Validation:
Add pre-processing checks to skip invalid or corrupt files (e.g., check file size, ensure the file is not locked by another process).
Memory Management:
For 2,500 files, memory usage is unlikely to be an issue, but if the files are very large, consider processing them in smaller batches to avoid memory overload.
Example Enhancements to Option #2
Here’s an example of how to add parallel processing and error logging to Option #2:
python
import logging
from concurrent.futures import ThreadPoolExecutor
import time
# Set up logging
logging.basicConfig(filename='processing.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# Modified process_file to include logging
def process_file(file_path):
try:
start_time = time.time()
doc = Document(file_path)
if not doc.paragraphs or all(not p.text.strip() for p in doc.paragraphs):
logging.info(f"Processed {file_path}: Blank file.")
return "Blank or No Title", [], [], "Blank file.", []
title = extract_title(doc)
present, missing = analyze_structure(doc)
summary = extract_file_summary(doc)
unexpected = extract_unexpected_headings(doc)
elapsed_time = time.time() - start_time
logging.info(f"Processed {file_path} in {elapsed_time:.2f} seconds.")
return title, present, missing, summary, unexpected
except Exception as e:
logging.error(f"Error processing {file_path}: {str(e)}")
return f"Error: {str(e)}", [], [], f"Error occurred: {str(e)}", []
# Modified process_all_folders to use parallel processing
def process_all_folders(base_path, output_excel_path, max_workers=4):
all_results = []
def process_single_file(args):
folder_path, file, folder_name, total_files, i = args
file_path = os.path.join(folder_path, file)
temp_converted = False
if file.endswith(".doc") and not file.endswith(".docx"):
try:
file_path = convert_doc_to_docx(file_path)
temp_converted = True
except Exception as e:
logging.error(f"Error converting {file}: {e}")
return None
title, present, missing, summary, unexpected = process_file(file_path)
result = {
"Folder Name": folder_name if i == 0 else "",
"File Count in Folder": total_files if i == 0 else "",
"File Name": file,
"Title Name": title,
"Sections Present": ", ".join(present) if present else "None",
"Sections Missing": ", ".join(missing) if missing else "None",
"Summary Content": summary,
"Other Headings Present (not in schema)": ", ".join(unexpected) if unexpected else "None"
}
if temp_converted:
try:
os.remove(file_path)
except Exception as e:
logging.error(f"Could not delete temp file {file_path}: {e}")
return result
tasks = []
for folder_name in os.listdir(base_path):
folder_path = os.path.join(base_path, folder_name)
if not os.path.isdir(folder_path):
continue
files = [f for f in os.listdir(folder_path) if (f.endswith(".docx") or f.endswith(".doc")) and not f.startswith("~$")]
total_files = len(files)
for i, file in enumerate(files):
tasks.append((folder_path, file, folder_name, total_files, i))
with ThreadPoolExecutor(max_workers=max_workers) as executor:
results = list(executor.map(process_single_file, tasks))
all_results = [r for r in results if r is not None]
df = pd.DataFrame(all_results)
pd.set_option('display.max_colwidth', None)
os.makedirs(os.path.dirname(output_excel_path), exist_ok=True)
df.to_excel(output_excel_path, index=False)
print(f"✅ Final Excel saved at: {output_excel_path}")
# Run the script
base_folder = r"D:\windows(c) users _mohan folders\Downloads\331 to 413"
output_file = os.path.join(os.path.dirname(__file__), "..", "output", "dk.xlsx")
process_all_folders(base_folder, output_file, max_workers=4)
Key Enhancements:
Parallel Processing: Uses ThreadPoolExecutor to process files in parallel, with max_workers=4 (adjust based on your CPU and I/O capacity).
Logging: Adds detailed logging to a file (processing.log) for tracking progress and errors.
Performance Monitoring: Measures and logs the time taken to process each file.
Conclusion
Best Method: Use Option #2 with the recommended enhancements (parallel processing, logging, etc.) for processing 2,500 files.
Why: It offers better accuracy, robustness, and maintainability, and the performance overhead of regex is negligible for this scale.
Next Steps: Test the enhanced script on a small subset of files (e.g., 50) to ensure it works as expected, then scale up to the full 2,500 files.