refactor!: Stable release for optima35

This commit is contained in:
Mr Finchum 2025-01-28 15:06:29 +00:00
parent 8f539d4097
commit dc32740309
6 changed files with 232 additions and 121 deletions

View file

@ -26,7 +26,7 @@ build:
- job: gitversion
artifacts: true
script:
- sed -i "s/0.0.1/${GitVersion_MajorMinorPatch}/" src/optima35/__init__.py
- sed -i "s/1.0.0/${GitVersion_MajorMinorPatch}/" src/optima35/__init__.py
- cat src/optima35/__init__.py
- python3 -m pip install build
- python3 -m build

View file

@ -1,5 +1,12 @@
# Changelog
## 1.0.0:
### Refactoring
- Added function descriptions for better clarity and maintainability.
- Introduced guidelines for each function, defining objectives and expected behavior.
---
## 0.12.x
### 0.12.2: Bug fixes
- Fixed missing lens in meta data
@ -11,11 +18,15 @@
### 0.12.0
- Versioning from pipeline.
---
## 0.7.x
### 0.7.0
- **BREAKING CHANGE:** GPS location must now be provided as a float instead of a string.
- Repo only: Pipline
---
## 0.6.x
### 0.6.8
- Repo only: Pipline
@ -46,6 +57,8 @@
- Working on to Publish on pypi
- Renaming of files and classes
---
## 0.5.x
### 0.5.0
### **OPTIMA35 0.5.0: Code Cleaning and Preparation for Split**
@ -57,6 +70,8 @@
- Updated **GUI** and **TUI** to work seamlessly with the new **OPTIMA35** class.
- Ensured compatibility with the newly organized codebase in the OPTIMA35 package.
---
## 0.4.x
### 0.4.1: Finished GUI and TUI
- Both **GUI** and **TUI** now fully utilize the `optima35` class for core functionality.
@ -82,6 +97,8 @@
- Improved readability, maintainability, and scalability of the project.
- Easier to test and debug individual components.
---
## 0.3.x
### 0.3.4: Features Finalized
- Core Features Completed:
@ -128,6 +145,8 @@
- Watermark is still in testing / alpha
- Original TUI version was forked and is still aviable, currently this branch includes the TUI version until the next minor version change.
---
## 0.2.x
### 0.2.1: Merge from TUI fork
- Ensure watermark is white with black borders.
@ -136,6 +155,8 @@
- **Cleaner folder structure**
- Moving files with classes to different folder to keep project cleaner.
---
## 0.1.x
### 0.1.1
- **Add Original to add Timestamp to Images**
@ -165,6 +186,8 @@
- At the start of the program, the user is asked to save default values, such as JPG quality, resize options, and more. This way, the settings don't have to be entered at every start. Upon starting, the user is prompted to confirm whether they want to keep the current settings from the settings file.
- Options for changing EXIF data are saved in exif_options.yaml. Here, you can enter all the models, lenses, etc., you would like to select within the program.
---
## 0.0.x
### 0.0.3: Enhanced Functionality - now useable
- **New Image Modification Functions:**

View file

@ -1,47 +1,55 @@
# **OPTIMA35**
[optima35](https://gitlab.com/CodeByMrFinchum/optima35) is a Python package for managing and editing images, with a focus on analog photography (using pillow and piexif). For a graphical user interface, see [OptimaLab35](https://gitlab.com/CodeByMrFinchum/OptimaLab35).
**OPTIMA35** stands for **Organizing, Processing, Tweaking Images, and Modifying Analogs from 35mm Film**. It is a Python package designed to simplify image editing and metadata management, providing an interface/API for handling image and EXIF data seamlessly. While OPTIMA35 was created with analog photography in mind—where scanned images often lack proper EXIF data or retain only scanner metadata—it is equally useful for digital images. Adding or managing EXIF data is invaluable for organizing private photo collections, making your photo library more structured and searchable.
## **Installation**
Install with pip (dependencies will be installed automatically):
```bash
pip install optima35
```
and the GUI with
```bash
pip install OptimaLab35
```
OPTIMA35 is a core package that acts as an interface for libraries like Pillow and piexif, simplifying image manipulation tasks. While it modifies images one at a time, it requires a dedicated program for flexible and batch processing. For a user-friendly graphical experience, consider using [OptimaLab35](https://gitlab.com/CodeByMrFinchum/OptimaLab35), a GUI designed specifically for OPTIMA35, also developed by me.
## **Overview**
Currently, there are no plans to create a formal API documentation. The code includes annotations and detailed function descriptions to explain its functionality. As this is a private hobby project, dedicating time to writing comprehensive documentation would take away from my limited free time.
**OPTIMA35** (**Organizing, Processing, Tweaking Images, and Modifying scanned Analogs from 35mm Film**) simplifies the editing and management of images and metadata. Though optimized for analog photography, it can handle any type of images.
---
## **Features**
### **Image Processing**
- Resize images
- Rename with custom order
- Grayscale conversion
- Brightness and contrast adjustment
- Resize images (upscale or downscale)
- Convert images to grayscale
- Adjust brightness and contrast
- Add customizable text-based watermarks
### **EXIF Management**
- Copy or add custom EXIF data
- Add GPS coordinates
- Add or modify EXIF dates
- Remove EXIF metadata
- Add EXIF data using a simple dictionary
- Copy EXIF data from the original image
- Remove EXIF metadata completely
- Add timestamps (e.g., original photo timestamp)
- Automatically adjust EXIF timestamps based on image file names
- Add GPS coordinates to images
### **Watermarking**
- Add customizable watermarks to images
### **Streamlined Integration**
- Handles all required EXIF byte conversions behind the scenes
- Provides an intuitive API for frequently needed operations
---
## **Installation**
Install the GUI (dependencies are installed automatically)
```bash
pip install OptimaLab35
```
Or in case you only want optima35 (dependencies are installed automatically):
```bash
pip install optima35
```
---
## **Current Status**
**Stable Release (v1.0)**
- The program follows semantic versioning (**major.minor.patch**).
- The current release is stable, and all changes within the same major version will remain backward compatible.
- Breaking changes, if any, will result in a new major version.
- Future development will primarily focus on the graphical user interface (OptimaLab35), with only minor updates or patches for OPTIMA35 as needed.
**Alpha Stage**
- Active development with frequent updates.
- Breaking changes may occur in minor version updates.
- Check the [CHANGELOG](https://gitlab.com/CodeByMrFinchum/optima35/-/blob/main/CHANGELOG.md?ref_type=heads) for details on changes and updates.
## **Contributing and Feedback**
Feedback, bug reports, and contributions are welcome! Please submit them through the [GitLab repository](https://gitlab.com/CodeByMrFinchum/optima35).
---
# Use of LLMs
In the interest of transparency, I disclose that Generative AI (GAI) large language models (LLMs), including OpenAIs ChatGPT and Ollama models (e.g., OpenCoder and Qwen2.5-coder), have been used to assist in this project.

View file

@ -1 +1 @@
__version__ = "0.0.1"
__version__ = "1.0.0"

View file

@ -11,7 +11,7 @@ class OptimaManager:
self.image_processor = ImageProcessor()
self.exif_handler = ExifHandler()
def modify_timestamp_in_exif(self, data_for_exif: dict, filename: str):
def _modify_timestamp_in_exif(self, data_for_exif: dict, filename: str):
""""Takes a dict formated for exif use by piexif and adjusts the date_time_original, changing the minutes and seconds to fit the number of the filname."""
last_three = filename[-3:len(filename)]
total_seconds = int(re.sub(r'\D+', '', last_three))
@ -22,101 +22,184 @@ class OptimaManager:
data_for_exif["date_time_original"] = new_time.strftime("%Y:%m:%d %H:%M:%S")
return data_for_exif
def process_image(self, # TODO: split into two classes, one for modification for one saving..
image_input_file,
image_output_file,
file_type = "jpg",
quality = 90,
compressing = 6,
optimize = False,
resize = None,
watermark = None,
font_size = 2,
grayscale = False,
brightness = None,
contrast = None,
dict_for_exif = None,
gps = None,
copy_exif = False,
save = True):
# Partly optimized by ChatGPT
# Open the image file
with self.image_processor.open_image(image_input_file) as img:
processed_img = img
image_name = os.path.basename(image_output_file) # for date adjustment
# Resize
if resize is not None:
processed_img = self.image_processor.resize_image(
image=processed_img, percent = resize
def _process_image(
self,
image_input_file: str,
resize: int = None,
watermark: str = None,
font_size: int = 2,
grayscale: bool = False,
brightness: float = None,
contrast: float = None
):
# My Code restructured by ChatGPT, but had to fix bugs
img = self.image_processor.open_image(image_input_file)
# Apply transformations
if resize is not None:
img = self.image_processor.resize_image(img, percent=resize)
if watermark is not None:
img = self.image_processor.add_watermark(img, watermark, font_size)
if grayscale:
img = self.image_processor.grayscale(img)
if brightness is not None:
img = self.image_processor.change_brightness(img, brightness)
if contrast is not None:
img = self.image_processor.change_contrast(img, contrast)
return img
def _handle_exif(
self,
image,
file_name,
dict_for_exif: dict = None,
gps: tuple[float, float] = None,
copy_exif: bool = False
):
# My Code restructured by ChatGPT, but had to fix bugs
# Build or copy EXIF data
if dict_for_exif:
if "date_time_original" in dict_for_exif:
dict_for_exif = self._modify_timestamp_in_exif(dict_for_exif, file_name)
exif_data = self.exif_handler.build_exif_bytes(
dict_for_exif, self.image_processor.get_image_size(image)
)
if gps:
exif_data = self.exif_handler.add_geolocation_to_exif(
exif_data, gps[0], gps[1]
)
elif copy_exif:
exif_data = self.exif_handler.get_exif_info(image)
else:
exif_data = None
return exif_data
# Watermark
if watermark is not None:
processed_img = self.image_processor.add_watermark(
processed_img, watermark, int(font_size)
)
def process_and_save_image(
self,
image_input_file: str,
image_output_file: str,
file_type: str = "jpg",
quality: int = 90,
compressing: int = 6,
optimize: bool = False,
resize: int = None,
watermark: str = None,
font_size: int = 2,
grayscale: bool = False,
brightness: float = None,
contrast: float = None,
dict_for_exif: dict = None,
gps: tuple[float, float] = None,
copy_exif: bool = False
) -> None:
"""
Processes an image with the given parameters and saves the output to a file.
# Grayscale
if grayscale:
processed_img = self.image_processor.grayscale(processed_img)
Args:
image_input_file (str): Path to the input image file.
image_output_file (str): Path to save the processed image.
file_type (str): Output image format ('jpg', 'png'). Defaults to 'jpg'.
quality (int): JPEG quality (1-100). Defaults to 90.
compressing (int): PNG compression level (0-9). Defaults to 6.
optimize (bool): Optimize image for smaller file size. Defaults to False.
resize (int, optional): Resize percentage. Defaults to None.
watermark (str, optional): Watermark text to add. Defaults to None.
font_size (int): Font size for the watermark. Defaults to 2.
grayscale (bool): Convert image to grayscale. Defaults to False.
brightness (float, optional): Adjust brightness (e.g., 1.2 for 20% brighter). Defaults to None.
contrast (float, optional): Adjust contrast (e.g., 1.5 for 50% higher contrast). Defaults to None.
dict_for_exif (dict, optional): EXIF metadata to insert. Defaults to None.
gps (tuple[float, float], optional): GPS coordinates (latitude, longitude). Defaults to None.
copy_exif (bool): Copy EXIF metadata from the input image. Defaults to False.
# Brightness
if brightness is not None:
processed_img = self.image_processor.change_brightness(
processed_img, brightness
)
Returns:
None
"""
# My Code restructured by ChatGPT
processed_img = self._process_image(
image_input_file,
resize,
watermark,
font_size,
grayscale,
brightness,
contrast,
)
# Contrast
if contrast is not None:
processed_img = self.image_processor.change_contrast(
processed_img, contrast
)
# Handle EXIF metadata
exif_piexif_format = self._handle_exif(
image = processed_img,
file_name = image_output_file,
dict_for_exif = dict_for_exif,
gps = gps,
copy_exif = copy_exif
)
# EXIF data handling
exif_piexif_format = None
if dict_for_exif: # todo: maybe move to ui and only accept complete exif dicts..
selected_exif = dict_for_exif
if "date_time_original" in dict_for_exif:
selected_exif = self.modify_timestamp_in_exif(selected_exif, image_name)
exif_piexif_format = self.exif_handler.build_exif_bytes(
selected_exif, self.image_processor.get_image_size(processed_img)
)
# Save the image
self.image_processor.save_image(
image = processed_img,
path = image_output_file,
piexif_exif_data = exif_piexif_format,
file_type = file_type,
jpg_quality = quality,
png_compressing = compressing,
optimize = optimize,
)
# GPS data
if gps is not None:
latitude = float(gps[0])
longitude = float(gps[1])
exif_piexif_format = self.exif_handler.add_geolocation_to_exif(exif_piexif_format, latitude, longitude)
def process_image_object(
self,
image_input_file: str,
resize: int = None,
watermark: str = None,
font_size: int = 2,
grayscale: bool = False,
brightness: float = None,
contrast: float = None
):
"""
Processes an image with the given parameters and returns the modified image object.
# Copy EXIF data if selected, and ensure size is correct in exif data
elif copy_exif:
try:
og_exif = self.exif_handler.get_exif_info(img)
og_exif["Exif"][40962], og_exif["Exif"][40963] = self.image_processor.get_image_size(processed_img)
exif_piexif_format = og_exif
except Exception:
print("Copying EXIF data selected, but no EXIF data is available in the original image file.")
Args:
image_input_file (str): Path to the input image file.
resize (int, optional): Resize percentage. Defaults to None.
watermark (str, optional): Watermark text to add. Defaults to None.
font_size (int): Font size for the watermark. Defaults to 2.
grayscale (bool): Convert image to grayscale. Defaults to False.
brightness (float, optional): Adjust brightness. Defaults to None.
contrast (float, optional): Adjust contrast. Defaults to None.
if save:
# Save the processed image
self.image_processor.save_image(
image = processed_img,
path = image_output_file,
piexif_exif_data = exif_piexif_format,
file_type = file_type,
jpg_quality = quality,
png_compressing = compressing,
optimize = optimize
)
else:
return self.image_processor.convert_pil_to_qtimage(processed_img)
Returns:
Image: The processed image object.
"""
# My Code restructured by ChatGPT
processed_img = self._process_image(
image_input_file,
resize,
watermark,
font_size,
grayscale,
brightness,
contrast,
)
return self.image_processor.convert_pil_to_qtimage(processed_img)
def insert_dict_to_image(self, exif_dict, image_path, gps = None):
def insert_exif_to_image(self, exif_dict: dict, image_path: str, gps: tuple[float, float] = None) -> None:
"""
Inserts EXIF metadata into an image.
Args:
exif_data (dict): A dictionary containing EXIF metadata as key-value pairs (e.g., strings, integers).
image_path (str): Absolute path to the target image file.
gps (tuple[float, float], optional): GPS coordinates as a tuple (latitude, longitude). Defaults to None.
Returns:
None: The function modifies the image file in place.
"""
# Restructured by ChatGPT
image_name, ending = os.path.splitext(os.path.basename(image_path))
img = self.image_processor.open_image(image_path)
selected_exif = exif_dict
if "date_time_original" in exif_dict:
selected_exif = self.modify_timestamp_in_exif(selected_exif, image_name)
selected_exif = self._modify_timestamp_in_exif(selected_exif, image_name)
exif_piexif_format = self.exif_handler.build_exif_bytes(
selected_exif, self.image_processor.get_image_size(img)

View file

@ -35,18 +35,15 @@ class ImageProcessor:
def resize_image(self, image, percent, resample = True):
"""Resize an image by giving a percent."""
new_size = tuple(int(x * (percent / 100)) for x in image.size)
if resample:
resized_image = image.resize(new_size)
else:
resized_image = image.resize((new_size),resample=Image.Resampling.NEAREST)
resized_image = image.resize(new_size)
return resized_image
def add_watermark(self, image, text, font_size_percentage):
"""Addes a watermark to the image using default os font."""
drawer = ImageDraw.Draw(image)
imagewidth, imageheight = image.size
margin = (imageheight / 100 ) * 2 # margin dynamic, 2% of image size
font_size = imagewidth * (font_size_percentage / 100)
margin = (imageheight / 100) * 2 # margin dynamic, 2% of image size
font_size = (imagewidth / 100) * font_size_percentage
try: # Try loading front, if notaviable return unmodified image
font = ImageFont.load_default(font_size)
@ -80,7 +77,7 @@ class ImageProcessor:
elif file_type == "png":
save_params["compress_level"] = png_compressing
elif file_type not in ["webp", "jpg", "png"]:
input(f"Type: {file_type} is not supported. Press Enter to continue...")
print(f"Type: {file_type} is not supported.")
return
# Add EXIF data if available
if piexif_exif_data is not None: