Opens all PNG images in folder_path named '{paper_name}-{index}.png', starting from index=1 up to the first missing, and returns them either as file-paths (if return_path=True) or as PIL.Image objects. If img_format!='png', each PNG is downsampled to fit within max_size (pr
(
folder_path,
paper_name,
return_path=False,
format='png',
max_size=(700, 700),
quality=80
)
| 721 | return question_only, answers, aspects |
| 722 | |
| 723 | def open_folder_images( |
| 724 | folder_path, |
| 725 | paper_name, |
| 726 | return_path=False, |
| 727 | format='png', |
| 728 | max_size=(700, 700), |
| 729 | quality=80 |
| 730 | ): |
| 731 | """ |
| 732 | Opens all PNG images in folder_path named '{paper_name}-{index}.png', |
| 733 | starting from index=1 up to the first missing, and returns them |
| 734 | either as file-paths (if return_path=True) or as PIL.Image objects. |
| 735 | |
| 736 | If img_format!='png', each PNG is downsampled to fit within max_size |
| 737 | (preserving aspect ratio), converted to RGB, and saved into an |
| 738 | in-memory JPEG with the given quality, optimize and progressive flags. |
| 739 | """ |
| 740 | images = [] |
| 741 | index = 1 |
| 742 | |
| 743 | while True: |
| 744 | png_name = f"{paper_name}-{index}.png" |
| 745 | path = os.path.join(folder_path, png_name) |
| 746 | if not os.path.isfile(path): |
| 747 | break |
| 748 | |
| 749 | if format == 'png': |
| 750 | if return_path: |
| 751 | images.append(path) |
| 752 | else: |
| 753 | images.append(Image.open(path)) |
| 754 | else: |
| 755 | # 1) Load and downsample |
| 756 | with Image.open(path) as im: |
| 757 | thumb = im.copy() |
| 758 | thumb.thumbnail(max_size, resample=Image.LANCZOS) |
| 759 | |
| 760 | # 2) Convert & compress to JPEG in-memory |
| 761 | rgb = thumb.convert("RGB") |
| 762 | buf = BytesIO() |
| 763 | rgb.save( |
| 764 | buf, |
| 765 | format="JPEG", |
| 766 | quality=quality, # e.g. 80–90 |
| 767 | optimize=True, # extra pass to strip redundant data |
| 768 | progressive=True # for incremental rendering |
| 769 | ) |
| 770 | buf.seek(0) |
| 771 | |
| 772 | if return_path: |
| 773 | # we return a tuple of (fake-jpg-filename, buffer) |
| 774 | jpg_name = png_name.rsplit('.', 1)[0] + '.jpg' |
| 775 | images.append((jpg_name, buf)) |
| 776 | else: |
| 777 | images.append(Image.open(buf)) |
| 778 | |
| 779 | index += 1 |
| 780 |
no test coverage detected