### Install dependencies via requirements.txt Source: https://github.com/kichangkim/deepdanbooru/blob/master/README.md Use the provided requirements file to install all necessary Python packages. ```bash > pip install -r requirements.txt ``` -------------------------------- ### Start project training Source: https://github.com/kichangkim/deepdanbooru/blob/master/README.md Begin the training process within the specified project folder. ```bash > deepdanbooru train-project [your_project_folder] ``` -------------------------------- ### Install DeepDanbooru package Source: https://github.com/kichangkim/deepdanbooru/blob/master/README.md Install the package using pip. Use the tensorflow extra to include the tensorflow dependency. ```bash > # default installation > pip install . > # with tensorflow package > pip install .[tensorflow] ``` -------------------------------- ### Create a training project Source: https://github.com/kichangkim/deepdanbooru/blob/master/README.md Initialize a new project folder for training. ```bash > deepdanbooru create-project [your_project_folder] ``` -------------------------------- ### Prepare training database Source: https://github.com/kichangkim/deepdanbooru/blob/master/README.md Convert dataset tags into system tags for training. ```bash > deepdanbooru make-training-database [your_dataset_sqlite_path] [your_filtered_sqlite_path] ``` -------------------------------- ### Create DeepDanbooru Project Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Initializes a new DeepDanbooru project directory with a default configuration file (`project.json`). This sets up the basic structure for training a custom model. ```bash # Create a new training project deepdanbooru create-project ./my_project ``` ```json # Default project.json contents include: # - image_width: 299, image_height: 299 # - model: "resnet_custom_v2" # - minibatch_size: 32 # - epoch_count: 10 # - optimizer: "adam", learning_rate: 0.001 # - loss: "binary_crossentropy" # - rotation_range: [0.0, 360.0] # - scale_range: [0.9, 1.1] # - shift_range: [-0.1, 0.1] ``` -------------------------------- ### Load Full Project Context Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Loads the entire project configuration, model, and tags simultaneously for streamlined inference. ```python import deepdanbooru as dd # Load entire project project_context, model, tags = dd.project.load_project("./my_project") # Access configuration print(f"Image size: {project_context['image_width']}x{project_context['image_height']}") print(f"Model type: {project_context['model']}") print(f"Total tags: {len(tags)}") # Use model for inference image = dd.data.load_image_for_evaluate("/path/to/image.jpg", width=project_context['image_width'], height=project_context['image_height']) # Reshape for batch prediction image = image.reshape((1, *image.shape)) predictions = model.predict(image)[0] # Get tags above threshold threshold = 0.5 for i, tag in enumerate(tags): if predictions[i] >= threshold: print(f"({predictions[i]:.3f}) {tag}") ``` -------------------------------- ### Create and Load Custom Tags Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Demonstrates how to create a custom tag file and load it into the DeepDanbooru environment. ```python custom_tags = ["1girl", "1boy", "long_hair", "short_hair", "blue_eyes", "rating:general"] with open("/path/to/custom_tags.txt", "w") as f: f.write("\n".join(custom_tags)) # Load custom tags tags = dd.data.load_tags("/path/to/custom_tags.txt") ``` -------------------------------- ### Evaluate Project via CLI Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Use a simplified interface to evaluate images or folders against a trained project. ```bash deepdanbooru evaluate-project ./my_project /path/to/image.jpg ``` ```bash deepdanbooru evaluate-project ./my_project /path/to/images_folder ``` ```bash deepdanbooru evaluate-project ./my_project /path/to/image.jpg \ --threshold 0.7 ``` -------------------------------- ### Project folder structure Source: https://github.com/kichangkim/deepdanbooru/blob/master/README.md The minimal file structure required for a training project. ```text MyProject/ ├── project.json └── tags.txt ``` -------------------------------- ### dd.project.load_project Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Loads the complete project context, model, and tags from a directory. ```APIDOC ## load_project ### Description Loads the entire project configuration, model, and tag list from the specified directory. ### Parameters - **project_path** (str) - Required - Path to the project directory. ### Response - **tuple** - Returns (project_context, model, tags). ``` -------------------------------- ### Create Training Database Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Generates a filtered SQLite database for training from a source database. Allows filtering by post ID range, inclusion of deleted posts, and database optimization. Automatically adds content rating tags. ```bash # Basic database creation deepdanbooru make-training-database \ /path/to/source_danbooru.sqlite \ /path/to/filtered_training.sqlite ``` ```bash # Filter by post ID range deepdanbooru make-training-database \ /path/to/source.sqlite \ /path/to/output.sqlite \ --start-id 1 \ --end-id 5000000 ``` ```bash # Include deleted posts and optimize database deepdanbooru make-training-database \ /path/to/source.sqlite \ /path/to/output.sqlite \ --use-deleted \ --vacuum \ --overwrite ``` ```bash # Custom chunk size for large databases deepdanbooru make-training-database \ /path/to/source.sqlite \ /path/to/output.sqlite \ --chunk-size 10000000 \ --vacuum ``` ```text # The output database will have posts table with: # - id, md5, file_ext, tag_string, tag_count_general # - System tags added: rating:general, rating:sensitive, # rating:questionable, rating:explicit ``` -------------------------------- ### Train DeepDanbooru Project Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Initiates the training process for a DeepDanbooru model using the project configuration. Supports training from scratch or continuing from a pre-trained model. Requires `project.json` to be configured with training parameters. ```bash # Start training from scratch deepdanbooru train-project ./my_project ``` ```bash # Continue training from a source model deepdanbooru train-project ./my_project \ --source-model /path/to/pretrained_model.keras ``` ```json # Before training, configure project.json: # { # "image_width": 299, # "image_height": 299, # "database_path": "/path/to/training.sqlite", # "minimum_tag_count": 20, # "model": "resnet_custom_v2", # Options: resnet_152, resnet_custom_v1-v4 # "minibatch_size": 32, # "epoch_count": 10, # ``` -------------------------------- ### Generate Grad-CAM Visualizations Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Create heatmaps to visualize which image regions contribute to specific tag predictions. ```bash deepdanbooru grad-cam ./my_project /path/to/image.jpg ./output_folder ``` ```bash deepdanbooru grad-cam ./my_project /path/to/images ./output_folder ``` ```bash deepdanbooru grad-cam ./my_project /path/to/image.jpg ./output \ --threshold 0.7 ``` -------------------------------- ### Evaluate Project CLI Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Evaluates images using project settings with a simpler interface. Designed for quick evaluation of images or folders against a trained project. ```APIDOC ## Evaluate Project ### Description Evaluates images using project settings with a simpler interface. Designed for quick evaluation of images or folders against a trained project. ### Method CLI command ### Endpoint deepdanbooru evaluate-project ### Parameters #### Path Parameters - **project_path** (string) - Required - Path to the DeepDanbooru project directory. - **target_path** (string) - Required - Path to the image file or folder to evaluate. #### Query Parameters - **--threshold** (float) - Optional - Confidence threshold for tag prediction (default: 0.5). ### Request Example ```bash deepdanbooru evaluate-project ./my_project /path/to/image.jpg ``` ### Response #### Success Response - **Tags** (list of strings) - Predicted tags with confidence scores. #### Response Example ``` Tags of /path/to/image.jpg: (0.987) 1girl (0.923) long_hair ``` ``` -------------------------------- ### Load Project Tags Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Retrieves the tag list associated with a project, which must match the model output order. ```python import deepdanbooru as dd # Load tags tags = dd.project.load_tags_from_project("./my_project") print(f"Total tags: {len(tags)}") print(f"First 10 tags: {tags[:10]}") print(f"Last 5 tags (system tags): {tags[-5:]}") ``` -------------------------------- ### Create TensorFlow Dataset with Augmentation Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Prepares image paths and tags into a TensorFlow dataset with specified data augmentation parameters for training. ```python import deepdanbooru as dd # Prepare training data image_paths = ["/path/to/img1.jpg", "/path/to/img2.jpg"] tag_strings = ["1girl long_hair", "1boy short_hair"] tags = ["1girl", "1boy", "long_hair", "short_hair"] # Create dataset wrapper with augmentation dataset_wrapper = dd.data.DatasetWrapper( (image_paths, tag_strings), tags, width=299, height=299, scale_range=[0.9, 1.1], # Random scaling rotation_range=[0.0, 360.0], # Random rotation shift_range=[-0.1, 0.1] # Random translation ) # Get TensorFlow dataset minibatch_size = 32 dataset = dataset_wrapper.get_dataset(minibatch_size) # Iterate through batches for x_batch, y_batch in dataset: print(f"Input batch shape: {x_batch.shape}") # (32, 299, 299, 3) print(f"Labels batch shape: {y_batch.shape}") # (32, num_tags) break ``` -------------------------------- ### Evaluate Images with DeepDanbooru Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Demonstrates how to evaluate images using a loaded model and tags, supporting both file paths and BytesIO objects. ```python # Load model and tags from project model = dd.project.load_model_from_project("./my_project") tags = dd.project.load_tags_from_project("./my_project") # Evaluate image from file path threshold = 0.5 for tag, score in dd.commands.evaluate_image( "/path/to/image.jpg", model, tags, threshold ): print(f"({score:.3f}) {tag}") # Evaluate image from BytesIO (useful for web applications) with open("/path/to/image.jpg", "rb") as f: image_bytes = BytesIO(f.read()) for tag, score in dd.commands.evaluate_image( image_bytes, model, tags, threshold ): print(f"({score:.3f}) {tag}") ``` -------------------------------- ### Evaluate Images via CLI Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Perform tag estimation on single images, multiple files, or entire directories with configurable thresholds and GPU support. ```bash deepdanbooru evaluate /path/to/image.jpg \ --project-path ./my_project \ --threshold 0.5 ``` ```bash deepdanbooru evaluate image1.jpg image2.png image3.gif \ --project-path ./my_project \ --threshold 0.7 ``` ```bash deepdanbooru evaluate /path/to/images_folder \ --project-path ./my_project \ --allow-folder \ --threshold 0.5 ``` ```bash deepdanbooru evaluate /path/to/images \ --project-path ./my_project \ --allow-folder \ --save-txt \ --threshold 0.5 ``` ```bash deepdanbooru evaluate /path/to/image.jpg \ --model-path /path/to/model.keras \ --tags-path /path/to/tags.txt \ --threshold 0.5 ``` ```bash deepdanbooru evaluate /path/to/image.jpg \ --project-path ./my_project \ --allow-gpu \ --verbose \ --threshold 0.5 ``` ```bash deepdanbooru evaluate /path/to/folder \ --project-path ./my_project \ --allow-folder \ --folder-filters "*.[Pp][Nn][Gg],*.[Jj][Pp][Gg]" ``` -------------------------------- ### Load Training Image Records Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Extracts image paths and tag strings from a SQLite database for training purposes. ```python import deepdanbooru as dd # Load training records with minimum tag count filter image_records = dd.data.load_image_records( "/path/to/training.sqlite", minimum_tag_count=20 ) print(f"Total training images: {len(image_records)}") # Each record is a tuple of (image_path, tag_string) for image_path, tag_string in image_records[:5]: print(f"Image: {image_path}") print(f"Tags: {tag_string[:100]}...") print() ``` -------------------------------- ### Dataset folder structure Source: https://github.com/kichangkim/deepdanbooru/blob/master/README.md The required directory layout for input images and the SQLite database. ```text MyDataset/ ├── images/ │ ├── 00/ │ │ ├── 00000000000000000000000000000000.jpg │ │ ├── ... │ ├── 01/ │ │ ├── 01000000000000000000000000000000.jpg │ │ ├── ... │ └── ff/ │ ├── ff000000000000000000000000000000.jpg │ ├── ... └── my-dataset.sqlite ``` -------------------------------- ### Load Model from Project Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Loads the Keras model with optional compilation settings for inference or training control. ```python import deepdanbooru as dd # Load model with compilation (default) model = dd.project.load_model_from_project("./my_project") # Load model without compilation (faster, for inference only) model = dd.project.load_model_from_project("./my_project", compile_model=False) # Check model architecture print(f"Input shape: {model.input_shape}") # (None, 299, 299, 3) print(f"Output shape: {model.output_shape}") # (None, num_tags) # Use for batch inference import numpy as np batch_images = np.random.rand(4, 299, 299, 3).astype(np.float32) batch_predictions = model.predict(batch_images) print(f"Predictions shape: {batch_predictions.shape}") # (4, num_tags) ``` -------------------------------- ### Evaluate images Source: https://github.com/kichangkim/deepdanbooru/blob/master/README.md Run tag estimation on image files or folders using a trained project. ```bash > deepdanbooru evaluate [image_file_path or folder]... --project-path [your_project_folder] --allow-folder ``` -------------------------------- ### Preprocess Images for Evaluation Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Handles image loading, resizing, and normalization. Supports raw 0-255 or normalized 0-1 ranges. ```python import deepdanbooru as dd # Load and preprocess image with default normalization (0-1 range) image = dd.data.load_image_for_evaluate( "/path/to/image.jpg", width=299, height=299 ) print(f"Image shape: {image.shape}") # (299, 299, 3) print(f"Value range: {image.min():.2f} to {image.max():.2f}") # 0.00 to 1.00 # Load without normalization (0-255 range) image_raw = dd.data.load_image_for_evaluate( "/path/to/image.jpg", width=299, height=299, normalize=False ) print(f"Raw value range: {image_raw.min():.0f} to {image_raw.max():.0f}") # 0 to 255 # Load from BytesIO from io import BytesIO with open("/path/to/image.png", "rb") as f: image_bytes = BytesIO(f.read()) image = dd.data.load_image_for_evaluate(image_bytes, width=299, height=299) ``` -------------------------------- ### Create ResNet Models for Multi-label Classification Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Generates various ResNet architectures optimized for multi-label image classification and compiles them for training. ```python import deepdanbooru as dd import tensorflow as tf # Define input shape and output dimensions input_shape = (299, 299, 3) output_dim = 10000 # Number of tags # Create input tensor inputs = tf.keras.Input(shape=input_shape, dtype=tf.float32) # Create ResNet-152 (original architecture) outputs = dd.model.resnet.create_resnet_152(inputs, output_dim) model = tf.keras.Model(inputs=inputs, outputs=outputs, name="resnet_152") # Create custom v2 (deep, narrow - default for DeepDanbooru) outputs = dd.model.resnet.create_resnet_custom_v2(inputs, output_dim) model = tf.keras.Model(inputs=inputs, outputs=outputs, name="resnet_custom_v2") # Compile model for training model.compile( optimizer=tf.optimizers.Adam(0.001), loss=tf.keras.losses.BinaryCrossentropy(), metrics=[tf.keras.metrics.Precision(), tf.keras.metrics.Recall()] ) print(f"Model: {model.input_shape} -> {model.output_shape}") ``` -------------------------------- ### Grad-CAM Visualization CLI Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Generates Grad-CAM (Gradient-weighted Class Activation Mapping) visualizations to understand which image regions contribute to specific tag predictions. Creates activation heatmaps for each predicted tag. ```APIDOC ## Grad-CAM Visualization ### Description Generates Grad-CAM (Gradient-weighted Class Activation Mapping) visualizations to understand which image regions contribute to specific tag predictions. Creates activation heatmaps for each predicted tag. ### Method CLI command ### Endpoint deepdanbooru grad-cam ### Parameters #### Path Parameters - **project_path** (string) - Required - Path to the DeepDanbooru project directory. - **input_path** (string) - Required - Path to the input image or folder. - **output_folder** (string) - Required - Directory to save the Grad-CAM visualizations. #### Query Parameters - **--threshold** (float) - Optional - Confidence threshold for tag selection (default: 0.5). ### Request Example ```bash deepdanbooru grad-cam ./my_project /path/to/image.jpg ./output_folder ``` ### Response #### Success Response - **Files** - Grad-CAM heatmaps and masked images saved to the specified output folder. #### Response Example ``` output_folder/ └── image_name/ ├── input.png # Original input image ├── result-{tag}.png # Gradient heatmap for each tag └── result-{tag}-masked.png # Image masked by activation ``` ``` -------------------------------- ### Download tags from Danbooru Source: https://github.com/kichangkim/deepdanbooru/blob/master/README.md Fetch the latest tags from the Danbooru server. Requires a valid account and API key. ```bash > deepdanbooru download-tags [your_project_folder] --username [your_danbooru_account] --api-key [your_danbooru_api_key] ``` -------------------------------- ### Download Danbooru Tags Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Downloads tag definitions from the Danbooru API to create `tags.txt` and related files. Requires Danbooru username and API key for authentication. Supports custom limits for tags and minimum post counts, and can overwrite existing files. ```bash # Download tags with default settings (10000 tags per category, min 500 posts) deepdanbooru download-tags ./my_project \ --username your_danbooru_username \ --api-key your_danbooru_api_key ``` ```bash # Download with custom limits deepdanbooru download-tags ./my_project \ --username your_danbooru_username \ --api-key your_danbooru_api_key \ --limit 5000 \ --minimum-post-count 1000 ``` ```bash # Overwrite existing tags file deepdanbooru download-tags ./my_project \ --username your_danbooru_username \ --api-key your_danbooru_api_key \ --overwrite ``` ```text # Output files created: # - tags.txt # Combined tag list for training # - tags-general.txt # General category tags # - tags-character.txt # Character category tags # - categories.json # Tag category metadata # - tags_log.json # Download log with parameters ``` -------------------------------- ### dd.data.load_image_for_evaluate Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Loads and preprocesses an image for model evaluation. ```APIDOC ## load_image_for_evaluate ### Description Handles resizing, padding, and normalization of images for inference. ### Parameters - **image_path_or_bytes** (str/BytesIO) - Required - Source image. - **width** (int) - Required - Target width. - **height** (int) - Required - Target height. - **normalize** (bool) - Optional - Whether to normalize pixel values to 0-1 range (default: True). ``` -------------------------------- ### SQLite table structure Source: https://github.com/kichangkim/deepdanbooru/blob/master/README.md The required schema for the SQLite database file. ```text posts ├── id (INTEGER) ├── md5 (TEXT) ├── file_ext (TEXT) ├── tag_string (TEXT) └── tag_count_general (INTEGER) ``` -------------------------------- ### dd.data.load_image_records Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Loads training image records from a SQLite database. ```APIDOC ## load_image_records ### Description Retrieves file paths and tag strings from a training database. ### Parameters - **db_path** (str) - Required - Path to the SQLite database. - **minimum_tag_count** (int) - Optional - Filter records by minimum tag count. ``` -------------------------------- ### Evaluate Images CLI Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Estimates tags for input images using a trained model. Supports single images, multiple images, and recursive folder processing. Can save results to text files and configure confidence thresholds. ```APIDOC ## Evaluate Images ### Description Estimates tags for input images using a trained model. Supports single images, multiple images, and recursive folder processing. Can save results to text files and configure confidence thresholds. ### Method CLI command ### Endpoint deepdanbooru evaluate ### Parameters #### Path Parameters - **image_path** (string) - Required - Path to the image file, multiple images, or a folder. #### Query Parameters - **--project-path** (string) - Optional - Path to the DeepDanbooru project directory. - **--threshold** (float) - Optional - Confidence threshold for tag prediction (default: 0.5). - **--allow-folder** - Optional - Flag to enable recursive folder processing. - **--save-txt** - Optional - Flag to save tags to text files alongside images. - **--model-path** (string) - Optional - Path to a specific Keras model file. - **--tags-path** (string) - Optional - Path to a specific tags file. - **--allow-gpu** - Optional - Flag to enable GPU acceleration. - **--verbose** - Optional - Flag for verbose output. - **--folder-filters** (string) - Optional - Filters for files within folders (e.g., "*.[Pp][Nn][Gg],*.[Jj][Pp][Gg]"). ### Request Example ```bash deepdanbooru evaluate /path/to/image.jpg \ --project-path ./my_project \ --threshold 0.5 ``` ### Response #### Success Response - **Tags** (list of strings) - Predicted tags with confidence scores. #### Response Example ``` Tags of /path/to/image.jpg: (0.987) 1girl (0.923) long_hair (0.856) blue_eyes (0.721) school_uniform ``` ``` -------------------------------- ### Load Tags from Text File Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Reads a newline-separated list of tags from a plain text file. ```python import deepdanbooru as dd # Load tags from file tags = dd.data.load_tags("/path/to/tags.txt") print(f"Loaded {len(tags)} tags") ``` -------------------------------- ### Tags file format Source: https://github.com/kichangkim/deepdanbooru/blob/master/README.md The format for the tags.txt file, which contains newline-separated tags. ```text 1girl ahoge ... ``` -------------------------------- ### Convert Model to TFLite Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Transform Keras models into TensorFlow Lite format for mobile or edge deployment. ```bash deepdanbooru conv2tflite \ --project-path ./my_project \ --save-path ./model.tflite ``` ```bash deepdanbooru conv2tflite \ --model-path /path/to/model.keras \ --save-path ./model.tflite ``` ```bash deepdanbooru conv2tflite \ --project-path ./my_project \ --save-path ./model.tflite \ --optimize-experimental-sparsity ``` ```bash deepdanbooru conv2tflite \ --project-path ./my_project \ --save-path ./model.tflite \ --verbose ``` -------------------------------- ### Convert to TFLite CLI Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Converts a trained Keras model to TensorFlow Lite format for mobile and edge deployment. Supports optimization options for reduced model size. ```APIDOC ## Convert to TFLite ### Description Converts a trained Keras model to TensorFlow Lite format for mobile and edge deployment. Supports optimization options for reduced model size. ### Method CLI command ### Endpoint deepdanbooru conv2tflite ### Parameters #### Query Parameters - **--project-path** (string) - Optional - Path to the DeepDanbooru project directory. - **--model-path** (string) - Optional - Path to a specific Keras model file. - **--save-path** (string) - Required - Path to save the converted TFLite model. - **--optimize-experimental-sparsity** - Optional - Flag to enable experimental sparsity optimization. - **--verbose** - Optional - Flag for verbose output. ### Request Example ```bash deepdanbooru conv2tflite \ --project-path ./my_project \ --save-path ./model.tflite ``` ### Response #### Success Response - **File** - The converted TensorFlow Lite model file saved at the specified `save-path`. #### Response Example ``` Model successfully converted and saved to ./model.tflite ``` ``` -------------------------------- ### evaluate_image Function (Python API) Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Evaluates a single image and returns predicted tags with confidence scores. Accepts file paths or BytesIO objects for flexible input handling. ```APIDOC ## evaluate_image Function ### Description Evaluates a single image and returns predicted tags with confidence scores. Accepts file paths or BytesIO objects for flexible input handling. ### Method Python function ### Endpoint dd.evaluate_image ### Parameters #### Arguments - **image_input** (string or BytesIO) - Required - Path to the image file or a BytesIO object containing image data. - **project_path** (string) - Optional - Path to the DeepDanbooru project directory. - **model_path** (string) - Optional - Path to a specific Keras model file. - **tags_path** (string) - Optional - Path to a specific tags file. - **threshold** (float) - Optional - Confidence threshold for tag prediction (default: 0.5). - **allow_gpu** (bool) - Optional - Flag to enable GPU acceleration (default: False). - **verbose** (bool) - Optional - Flag for verbose output (default: False). ### Request Example ```python import deepdanbooru as dd import tensorflow as tf from io import BytesIO # Evaluate from file path tags = dd.evaluate_image('/path/to/image.jpg', project_path='./my_project', threshold=0.6) print(tags) # Evaluate from BytesIO object with open('/path/to/image.jpg', 'rb') as f: image_bytes = BytesIO(f.read()) tags_from_bytes = dd.evaluate_image(image_bytes, project_path='./my_project') print(tags_from_bytes) ``` ### Response #### Success Response - **tags** (list of tuples) - A list of tuples, where each tuple contains (tag_name, confidence_score). #### Response Example ``` [('1girl', 0.987), ('long_hair', 0.923), ('blue_eyes', 0.856)] ``` ``` -------------------------------- ### Python API Imports Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Required imports for utilizing the DeepDanbooru Python API. ```python import deepdanbooru as dd import tensorflow as tf from io import BytesIO ``` -------------------------------- ### Convert Keras Model to TensorFlow Lite Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Converts a trained Keras model to TensorFlow Lite format, with options for optimization and inference. ```python import deepdanbooru as dd import tensorflow as tf # Convert from project dd.commands.convert_to_tflite_from_from_saved_model( project_path="./my_project", model_path=None, save_path="./model.tflite", optimizations=[tf.lite.Optimize.DEFAULT], verbose=True ) # Convert from specific model file dd.commands.convert_to_tflite_from_from_saved_model( project_path=None, model_path="/path/to/model.keras", save_path="./model_optimized.tflite", optimizations=[ tf.lite.Optimize.DEFAULT, tf.lite.Optimize.EXPERIMENTAL_SPARSITY ], verbose=True ) # Use converted TFLite model for inference interpreter = tf.lite.Interpreter(model_path="./model.tflite") interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # Prepare input image = dd.data.load_image_for_evaluate("/path/to/image.jpg", 299, 299) input_data = image.reshape((1, 299, 299, 3)).astype('float32') # Run inference interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() predictions = interpreter.get_tensor(output_details[0]['index'])[0] ``` -------------------------------- ### dd.commands.evaluate_image Source: https://context7.com/kichangkim/deepdanbooru/llms.txt Evaluates an image file or byte stream against a loaded model and tag list to predict tags. ```APIDOC ## evaluate_image ### Description Evaluates an image and returns a list of predicted tags with their confidence scores. ### Parameters - **image_path_or_bytes** (str/BytesIO) - Required - The path to the image file or a BytesIO object. - **model** (Keras Model) - Required - The loaded Keras model. - **tags** (list) - Required - The list of tags corresponding to model outputs. - **threshold** (float) - Required - The minimum confidence score for a tag to be returned. ### Response - **Iterator** - Yields tuples of (tag, score). ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.