Skip to content

Instantly share code, notes, and snippets.

@shahpnmlab
Last active November 4, 2024 22:00
Show Gist options
  • Save shahpnmlab/d883ab7985b546613b1ff84dd62cbc82 to your computer and use it in GitHub Desktop.
Save shahpnmlab/d883ab7985b546613b1ff84dd62cbc82 to your computer and use it in GitHub Desktop.
copy_subset_frames_from_mdoc
from pathlib import Path
import mdocfile
import shutil
import typer
import logging
from typing import Optional
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
app = typer.Typer(no_args_is_help=True)
@app.command()
def main(
md_path: Optional[Path] = typer.Option(None, "--i", help="Path to directory containing mdoc files"),
md_name: Optional[str] = typer.Option(None, "--n", help="Name of mdoc file"),
src_dir: Optional[Path] = typer.Option(None, "--s", help="Path to where the frames are stored"),
dest_dir: Optional[Path] = typer.Option(None, "--d", help="Path where the frames should be copied to"),
save_frames_text_file: bool = typer.Option(False, "--save2txt", help="Just save file names to a text file")
) -> None:
"""
Process mdoc files and copy or list associated frames.
"""
try:
# Validate input parameters
if not md_path or not md_path.exists():
raise ValueError(f"Invalid or non-existent mdoc directory: {md_path}")
if not src_dir or not src_dir.exists():
raise ValueError(f"Invalid or non-existent source directory: {src_dir}")
if not save_frames_text_file and (not dest_dir or not dest_dir.exists()):
raise ValueError(f"Invalid or non-existent destination directory: {dest_dir}")
# Get list of mdoc files
mdocs = sorted(list(md_path.glob('*.mdoc')))
if not mdocs:
raise FileNotFoundError(f"No mdoc files found in {md_path}")
# Filter by name if specified
if md_name:
mdocs = [mdoc for mdoc in mdocs if mdoc.name == md_name]
if not mdocs:
raise FileNotFoundError(f"No mdoc file found with name: {md_name}")
# Process each mdoc file
for mdoc_file in mdocs:
logger.info(f"Processing mdoc file: {mdoc_file}")
md = mdocfile.read(mdoc_file)
if 'SubFramePath' not in md:
logger.warning(f"No SubFramePath found in {mdoc_file}")
continue
if save_frames_text_file:
# Save frame names to text file
output_file = dest_dir / f"{mdoc_file.stem}_frames.txt"
with open(output_file, 'w') as f:
for frame in md['SubFramePath']:
f.write(f"{frame.name}\n")
logger.info(f"Frame names saved to: {output_file}")
else:
# Copy frames to destination directory
for frame in md['SubFramePath']:
src_path = src_dir / frame.name
dest_path = dest_dir / frame.name
if not src_path.exists():
logger.warning(f"Source frame not found: {src_path}")
continue
try:
shutil.copy2(src_path, dest_path)
logger.info(f"Copied {frame.name} to {dest_path}")
except Exception as e:
logger.error(f"Error copying {frame.name}: {str(e)}")
except Exception as e:
logger.error(f"An error occurred: {str(e)}")
raise typer.Exit(code=1)
if __name__ == "__main__":
app()
@shahpnmlab
Copy link
Author

WIP

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment