Skip to content

API Reference

Query Functions

get_preset

Get a mineral preset dictionary by name.

from mineral_database import get_preset

diamond = get_preset('diamond')
print(diamond['cdl'])      # CDL string
print(diamond['system'])   # Crystal system
print(diamond['hardness']) # Mohs hardness

mineral_database.get_preset(name)

Get a crystal preset by name.

This is the primary compatibility function matching the original API.

Parameters:

Name Type Description Default
name str

Preset name (case-insensitive)

required

Returns:

Type Description
dict[str, Any] | None

Preset dictionary or None if not found

Source code in src/mineral_database/queries.py
def get_preset(name: str) -> dict[str, Any] | None:
    """Get a crystal preset by name.

    This is the primary compatibility function matching the original API.

    Args:
        name: Preset name (case-insensitive)

    Returns:
        Preset dictionary or None if not found
    """
    with get_connection(_db_path) as conn:
        mineral = get_mineral_by_id(conn, name.lower())
        if mineral:
            return mineral.to_dict()
    return None

get_mineral

Get a Mineral object by name.

from mineral_database import get_mineral

mineral = get_mineral('ruby')
print(mineral.id)           # 'ruby'
print(mineral.name)         # 'Ruby'
print(mineral.system)       # 'trigonal'
print(mineral.chemistry)    # 'Al2O3:Cr'
print(mineral.hardness)     # 9
print(mineral.ri)           # '1.762-1.770'
print(mineral.localities)   # ['Myanmar', 'Mozambique', ...]

mineral_database.get_mineral(name)

Get a Mineral object by name.

Parameters:

Name Type Description Default
name str

Preset name (case-insensitive)

required

Returns:

Type Description
Mineral | None

Mineral object or None if not found

Source code in src/mineral_database/queries.py
def get_mineral(name: str) -> Mineral | None:
    """Get a Mineral object by name.

    Args:
        name: Preset name (case-insensitive)

    Returns:
        Mineral object or None if not found
    """
    with get_connection(_db_path) as conn:
        return get_mineral_by_id(conn, name.lower())

list_presets

List preset names, optionally filtered by crystal system.

from mineral_database import list_presets

# All presets
all_presets = list_presets()

# Filter by system
cubic_presets = list_presets('cubic')
trigonal_presets = list_presets('trigonal')

mineral_database.list_presets(category=None)

List available preset names.

Parameters:

Name Type Description Default
category str | None

Optional crystal system or category to filter by

None

Returns:

Type Description
list[str]

List of preset names

Source code in src/mineral_database/queries.py
def list_presets(category: str | None = None) -> list[str]:
    """List available preset names.

    Args:
        category: Optional crystal system or category to filter by

    Returns:
        List of preset names
    """
    with get_connection(_db_path) as conn:
        if category:
            category = category.lower()
            # Check if it's a category
            presets = get_category_presets(conn, category)
            if presets:
                return presets
            # Check if it's a crystal system
            minerals = get_minerals_by_system(conn, category)
            return [m.id for m in minerals]
        # Return all presets
        minerals = get_all_minerals(conn)
        return sorted([m.id for m in minerals])

list_preset_categories

List all preset categories/tags.

from mineral_database import list_preset_categories

categories = list_preset_categories()
# ['cubic', 'hexagonal', 'trigonal', 'twins', ...]

mineral_database.list_preset_categories()

List available preset categories (crystal systems).

Source code in src/mineral_database/queries.py
def list_preset_categories() -> list[str]:
    """List available preset categories (crystal systems)."""
    with get_connection(_db_path) as conn:
        cursor = conn.execute(
            "SELECT DISTINCT system FROM minerals WHERE system IS NOT NULL ORDER BY system"
        )
        return [row[0] for row in cursor.fetchall()]

search_presets

Full-text search across mineral names and properties.

from mineral_database import search_presets

# Search by name
garnet_matches = search_presets('garnet')

# Search by property
red_gems = search_presets('red')

mineral_database.search_presets(query)

Search presets by name, mineral name, or chemistry.

Parameters:

Name Type Description Default
query str

Search term

required

Returns:

Type Description
list[str]

List of matching preset names

Source code in src/mineral_database/queries.py
def search_presets(query: str) -> list[str]:
    """Search presets by name, mineral name, or chemistry.

    Args:
        query: Search term

    Returns:
        List of matching preset names
    """
    query = query.lower()
    results = []

    with get_connection(_db_path) as conn:
        # Try FTS search first
        try:
            minerals = search_minerals(conn, query)
            results = [m.id for m in minerals]
        except Exception:
            # Fallback to simple LIKE search
            pass

        if not results:
            # Simple fallback search
            all_minerals = get_all_minerals(conn)
            for mineral in all_minerals:
                if (
                    query in mineral.id.lower()
                    or query in mineral.name.lower()
                    or query in mineral.chemistry.lower()
                    or query in mineral.description.lower()
                ):
                    results.append(mineral.id)

    return results

filter_minerals

Filter minerals by multiple criteria.

from mineral_database import filter_minerals

# Filter by system and hardness
hard_cubic = filter_minerals(system='cubic', min_hardness=8)

# Filter by optical properties
birefringent = filter_minerals(has_birefringence=True)

mineral_database.filter_minerals(system=None, min_hardness=None, max_hardness=None, has_twin=False)

Filter minerals by various criteria.

Parameters:

Name Type Description Default
system str | None

Filter by crystal system

None
min_hardness float | None

Minimum Mohs hardness

None
max_hardness float | None

Maximum Mohs hardness

None
has_twin bool

Only return minerals with twin laws

False

Returns:

Type Description
list[str]

List of matching preset names

Source code in src/mineral_database/queries.py
def filter_minerals(
    system: str | None = None,
    min_hardness: float | None = None,
    max_hardness: float | None = None,
    has_twin: bool = False,
) -> list[str]:
    """Filter minerals by various criteria.

    Args:
        system: Filter by crystal system
        min_hardness: Minimum Mohs hardness
        max_hardness: Maximum Mohs hardness
        has_twin: Only return minerals with twin laws

    Returns:
        List of matching preset names
    """
    results = []

    with get_connection(_db_path) as conn:
        if system:
            minerals = get_minerals_by_system(conn, system)
        else:
            minerals = get_all_minerals(conn)

        for mineral in minerals:
            # Check hardness
            try:
                hardness = float(str(mineral.hardness).split("-")[0])
                if min_hardness and hardness < min_hardness:
                    continue
                if max_hardness and hardness > max_hardness:
                    continue
            except (ValueError, TypeError):
                pass

            # Check twin
            if has_twin and not mineral.twin_law:
                continue

            results.append(mineral.id)

    return results

get_presets_by_form

Get presets that include a specific crystal form.

from mineral_database import get_presets_by_form

# Get all minerals with octahedral habit
octahedral = get_presets_by_form('octahedron')

mineral_database.get_presets_by_form(form_name)

Get presets that include a specific crystal form.

Parameters:

Name Type Description Default
form_name str

Form name (e.g., 'octahedron', 'cube')

required

Returns:

Type Description
list[str]

List of preset names

Source code in src/mineral_database/queries.py
def get_presets_by_form(form_name: str) -> list[str]:
    """Get presets that include a specific crystal form.

    Args:
        form_name: Form name (e.g., 'octahedron', 'cube')

    Returns:
        List of preset names
    """
    form_name = form_name.lower()
    results = []

    with get_connection(_db_path) as conn:
        minerals = get_all_minerals(conn)
        for mineral in minerals:
            if form_name in [f.lower() for f in mineral.forms]:
                results.append(mineral.id)

    return results

count_presets

Get total count of presets.

from mineral_database import count_presets

total = count_presets()
print(f"Database contains {total} presets")  # 94+

mineral_database.count_presets()

Get total number of presets in database.

Returns:

Type Description
int

Number of presets

Source code in src/mineral_database/queries.py
def count_presets() -> int:
    """Get total number of presets in database.

    Returns:
        Number of presets
    """
    with get_connection(_db_path) as conn:
        minerals = get_all_minerals(conn)
        return len(minerals)

Data Classes

Mineral

Full mineral data object.

from mineral_database import Mineral

@dataclass
class Mineral:
    id: str
    name: str
    cdl: str
    system: str
    point_group: str
    chemistry: Optional[str]
    hardness: Optional[float]
    description: Optional[str]
    sg: Optional[float]
    ri: Optional[str]
    birefringence: Optional[float]
    optical_character: Optional[str]
    dispersion: Optional[float]
    lustre: Optional[str]
    cleavage: Optional[str]
    fracture: Optional[str]
    pleochroism: Optional[str]
    twin_law: Optional[str]
    phenomenon: Optional[str]
    localities: List[str]
    forms: List[str]
    colors: List[str]
    treatments: List[str]
    inclusions: List[str]

mineral_database.Mineral dataclass

A mineral preset with crystallographic and gemmological properties.

Attributes:

Name Type Description
id str

Unique preset identifier (e.g., 'diamond', 'ruby')

name str

Display name (e.g., 'Diamond', 'Ruby')

cdl str

Crystal Description Language notation

system str

Crystal system (cubic, hexagonal, etc.)

point_group str

Hermann-Mauguin point group symbol

chemistry str

Chemical formula

hardness int | float | str

Mohs hardness (can be range like '5-7')

description str

Crystal habit description

localities list[str]

List of notable localities

forms list[str]

List of crystal forms present

sg float | str | None

Specific gravity (may be range string)

ri float | str | None

Refractive index (may be range string)

birefringence float | None

Birefringence value or None for isotropic

optical_character str | None

Optical character (Uniaxial +/-, Biaxial +/-, Isotropic)

dispersion float | None

Dispersion coefficient

lustre str | None

Surface lustre

cleavage str | None

Cleavage description

fracture str | None

Fracture type

pleochroism str | None

Pleochroism description

colors list[str]

List of possible colors

treatments list[str]

List of known treatments

inclusions list[str]

List of diagnostic inclusions

twin_law str | None

Associated twin law name

phenomenon str | None

Optical phenomenon (e.g., 'Adularescence')

note str | None

Additional notes

Source code in src/mineral_database/models.py
@dataclass
class Mineral:
    """A mineral preset with crystallographic and gemmological properties.

    Attributes:
        id: Unique preset identifier (e.g., 'diamond', 'ruby')
        name: Display name (e.g., 'Diamond', 'Ruby')
        cdl: Crystal Description Language notation
        system: Crystal system (cubic, hexagonal, etc.)
        point_group: Hermann-Mauguin point group symbol
        chemistry: Chemical formula
        hardness: Mohs hardness (can be range like '5-7')
        description: Crystal habit description
        localities: List of notable localities
        forms: List of crystal forms present

        # Optional gemmological properties
        sg: Specific gravity (may be range string)
        ri: Refractive index (may be range string)
        birefringence: Birefringence value or None for isotropic
        optical_character: Optical character (Uniaxial +/-, Biaxial +/-, Isotropic)
        dispersion: Dispersion coefficient
        lustre: Surface lustre
        cleavage: Cleavage description
        fracture: Fracture type
        pleochroism: Pleochroism description
        colors: List of possible colors
        treatments: List of known treatments
        inclusions: List of diagnostic inclusions

        # Optional special properties
        twin_law: Associated twin law name
        phenomenon: Optical phenomenon (e.g., 'Adularescence')
        note: Additional notes
    """

    # Required fields
    id: str
    name: str
    cdl: str
    system: str
    point_group: str
    chemistry: str
    hardness: int | float | str
    description: str

    # Common optional fields
    localities: list[str] = field(default_factory=list)
    forms: list[str] = field(default_factory=list)

    # Gemmological properties
    sg: float | str | None = None
    ri: float | str | None = None
    birefringence: float | None = None
    optical_character: str | None = None
    dispersion: float | None = None
    lustre: str | None = None
    cleavage: str | None = None
    fracture: str | None = None
    pleochroism: str | None = None
    # Structured pleochroism data for dichroscope lookup
    pleochroism_strength: str | None = None  # none|weak|moderate|strong|very_strong
    pleochroism_color1: str | None = None
    pleochroism_color2: str | None = None
    pleochroism_color3: str | None = None  # For trichroic gems
    pleochroism_notes: str | None = None
    colors: list[str] = field(default_factory=list)
    treatments: list[str] = field(default_factory=list)
    inclusions: list[str] = field(default_factory=list)

    # Special properties
    twin_law: str | None = None
    phenomenon: str | None = None
    note: str | None = None

    # Calculator-optimized numeric fields (parsed from RI/SG ranges)
    ri_min: float | None = None
    ri_max: float | None = None
    sg_min: float | None = None
    sg_max: float | None = None

    # Heat treatment temperatures (Celsius, from GIA/GEM-A data)
    heat_treatment_temp_min: float | None = None
    heat_treatment_temp_max: float | None = None

    # Synthetic/simulant classification
    origin: str = "natural"  # natural|synthetic|simulant|composite
    growth_method: str | None = None
    natural_counterpart_id: str | None = None

    def to_dict(self) -> dict[str, Any]:
        """Convert to dictionary representation."""
        result: dict[str, Any] = {
            "id": self.id,
            "name": self.name,
            "cdl": self.cdl,
            "system": self.system,
            "point_group": self.point_group,
            "chemistry": self.chemistry,
            "hardness": self.hardness,
            "description": self.description,
            "origin": self.origin,
        }

        # Add non-empty lists
        if self.localities:
            result["localities"] = self.localities
        if self.forms:
            result["forms"] = self.forms
        if self.colors:
            result["colors"] = self.colors
        if self.treatments:
            result["treatments"] = self.treatments
        if self.inclusions:
            result["inclusions"] = self.inclusions

        # Add optional fields if set
        optional = [
            "sg",
            "ri",
            "birefringence",
            "optical_character",
            "dispersion",
            "lustre",
            "cleavage",
            "fracture",
            "pleochroism",
            "pleochroism_strength",
            "pleochroism_color1",
            "pleochroism_color2",
            "pleochroism_color3",
            "pleochroism_notes",
            "twin_law",
            "phenomenon",
            "note",
            "ri_min",
            "ri_max",
            "sg_min",
            "sg_max",
            "heat_treatment_temp_min",
            "heat_treatment_temp_max",
            "growth_method",
            "natural_counterpart_id",
        ]
        for key in optional:
            value = getattr(self, key)
            if value is not None:
                result[key] = value

        return result

    @classmethod
    def from_dict(cls, id: str, data: dict[str, Any]) -> "Mineral":
        """Create Mineral from dictionary.

        Args:
            id: The preset identifier
            data: Dictionary of mineral properties

        Returns:
            Mineral instance
        """
        return cls(
            id=id,
            name=data.get("name", id.replace("-", " ").title()),
            cdl=data["cdl"],
            system=data.get("system", "cubic"),
            point_group=data.get("point_group", "m3m"),
            chemistry=data.get("chemistry", ""),
            hardness=data.get("hardness", 0),
            description=data.get("description", ""),
            localities=data.get("localities", []),
            forms=data.get("forms", []),
            sg=data.get("sg"),
            ri=data.get("ri"),
            birefringence=data.get("birefringence"),
            optical_character=data.get("optical_character"),
            dispersion=data.get("dispersion"),
            lustre=data.get("lustre"),
            cleavage=data.get("cleavage"),
            fracture=data.get("fracture"),
            pleochroism=data.get("pleochroism"),
            pleochroism_strength=data.get("pleochroism_strength"),
            pleochroism_color1=data.get("pleochroism_color1"),
            pleochroism_color2=data.get("pleochroism_color2"),
            pleochroism_color3=data.get("pleochroism_color3"),
            pleochroism_notes=data.get("pleochroism_notes"),
            colors=data.get("colors", []),
            treatments=data.get("treatments", []),
            inclusions=data.get("inclusions", []),
            twin_law=data.get("twin_law"),
            phenomenon=data.get("phenomenon"),
            note=data.get("note"),
            ri_min=data.get("ri_min"),
            ri_max=data.get("ri_max"),
            sg_min=data.get("sg_min"),
            sg_max=data.get("sg_max"),
            heat_treatment_temp_min=data.get("heat_treatment_temp_min"),
            heat_treatment_temp_max=data.get("heat_treatment_temp_max"),
            origin=data.get("origin", "natural"),
            growth_method=data.get("growth_method"),
            natural_counterpart_id=data.get("natural_counterpart_id"),
        )

from_dict(id, data) classmethod

Create Mineral from dictionary.

Parameters:

Name Type Description Default
id str

The preset identifier

required
data dict[str, Any]

Dictionary of mineral properties

required

Returns:

Type Description
Mineral

Mineral instance

Source code in src/mineral_database/models.py
@classmethod
def from_dict(cls, id: str, data: dict[str, Any]) -> "Mineral":
    """Create Mineral from dictionary.

    Args:
        id: The preset identifier
        data: Dictionary of mineral properties

    Returns:
        Mineral instance
    """
    return cls(
        id=id,
        name=data.get("name", id.replace("-", " ").title()),
        cdl=data["cdl"],
        system=data.get("system", "cubic"),
        point_group=data.get("point_group", "m3m"),
        chemistry=data.get("chemistry", ""),
        hardness=data.get("hardness", 0),
        description=data.get("description", ""),
        localities=data.get("localities", []),
        forms=data.get("forms", []),
        sg=data.get("sg"),
        ri=data.get("ri"),
        birefringence=data.get("birefringence"),
        optical_character=data.get("optical_character"),
        dispersion=data.get("dispersion"),
        lustre=data.get("lustre"),
        cleavage=data.get("cleavage"),
        fracture=data.get("fracture"),
        pleochroism=data.get("pleochroism"),
        pleochroism_strength=data.get("pleochroism_strength"),
        pleochroism_color1=data.get("pleochroism_color1"),
        pleochroism_color2=data.get("pleochroism_color2"),
        pleochroism_color3=data.get("pleochroism_color3"),
        pleochroism_notes=data.get("pleochroism_notes"),
        colors=data.get("colors", []),
        treatments=data.get("treatments", []),
        inclusions=data.get("inclusions", []),
        twin_law=data.get("twin_law"),
        phenomenon=data.get("phenomenon"),
        note=data.get("note"),
        ri_min=data.get("ri_min"),
        ri_max=data.get("ri_max"),
        sg_min=data.get("sg_min"),
        sg_max=data.get("sg_max"),
        heat_treatment_temp_min=data.get("heat_treatment_temp_min"),
        heat_treatment_temp_max=data.get("heat_treatment_temp_max"),
        origin=data.get("origin", "natural"),
        growth_method=data.get("growth_method"),
        natural_counterpart_id=data.get("natural_counterpart_id"),
    )

to_dict()

Convert to dictionary representation.

Source code in src/mineral_database/models.py
def to_dict(self) -> dict[str, Any]:
    """Convert to dictionary representation."""
    result: dict[str, Any] = {
        "id": self.id,
        "name": self.name,
        "cdl": self.cdl,
        "system": self.system,
        "point_group": self.point_group,
        "chemistry": self.chemistry,
        "hardness": self.hardness,
        "description": self.description,
        "origin": self.origin,
    }

    # Add non-empty lists
    if self.localities:
        result["localities"] = self.localities
    if self.forms:
        result["forms"] = self.forms
    if self.colors:
        result["colors"] = self.colors
    if self.treatments:
        result["treatments"] = self.treatments
    if self.inclusions:
        result["inclusions"] = self.inclusions

    # Add optional fields if set
    optional = [
        "sg",
        "ri",
        "birefringence",
        "optical_character",
        "dispersion",
        "lustre",
        "cleavage",
        "fracture",
        "pleochroism",
        "pleochroism_strength",
        "pleochroism_color1",
        "pleochroism_color2",
        "pleochroism_color3",
        "pleochroism_notes",
        "twin_law",
        "phenomenon",
        "note",
        "ri_min",
        "ri_max",
        "sg_min",
        "sg_max",
        "heat_treatment_temp_min",
        "heat_treatment_temp_max",
        "growth_method",
        "natural_counterpart_id",
    ]
    for key in optional:
        value = getattr(self, key)
        if value is not None:
            result[key] = value

    return result

Property Formatting

INFO_GROUPS

Property groups for display organization.

from mineral_database import INFO_GROUPS

# Groups: 'identification', 'physical', 'optical', 'crystallographic'
for group, props in INFO_GROUPS.items():
    print(f"{group}: {props}")

get_info_properties

Get formatted properties for display.

from mineral_database import get_info_properties

# Get FGA-style properties
props = get_info_properties('ruby', 'fga')
# Returns: {'name': 'Ruby', 'ri': '1.762-1.770', 'sg': 4.0, ...}

mineral_database.get_info_properties(preset_name, group_or_keys)

Get specific properties from a preset for info panel display.

Parameters:

Name Type Description Default
preset_name str

Name of the preset

required
group_or_keys str

Either a group name ('basic', 'full', 'fga', etc.) or comma-separated property keys

required

Returns:

Type Description
dict[str, Any]

Dictionary of property key -> value for display

Source code in src/mineral_database/queries.py
def get_info_properties(preset_name: str, group_or_keys: str) -> dict[str, Any]:
    """Get specific properties from a preset for info panel display.

    Args:
        preset_name: Name of the preset
        group_or_keys: Either a group name ('basic', 'full', 'fga', etc.)
                      or comma-separated property keys

    Returns:
        Dictionary of property key -> value for display
    """
    mineral = get_mineral(preset_name)
    if not mineral:
        return {}

    # Determine which keys to extract
    if group_or_keys in INFO_GROUPS:
        keys = INFO_GROUPS[group_or_keys]
    else:
        keys = [k.strip() for k in group_or_keys.split(",")]

    # Extract properties
    result = {}
    mineral_dict = mineral.to_dict()
    for key in keys:
        if key in mineral_dict:
            result[key] = mineral_dict[key]

    return result

get_property_label

Get display label for a property key.

from mineral_database import get_property_label

label = get_property_label('sg')  # 'SG'
label = get_property_label('ri')  # 'RI'

mineral_database.get_property_label(key)

Get display label for a property key.

Source code in src/mineral_database/models.py
def get_property_label(key: str) -> str:
    """Get display label for a property key."""
    return PROPERTY_LABELS.get(key, key.replace("_", " ").title())

format_property_value

Format a property value for display.

from mineral_database import format_property_value

value = format_property_value('sg', 4.0)       # '4.00'
value = format_property_value('hardness', 9)   # '9'

mineral_database.format_property_value(key, value)

Format a property value for display.

Parameters:

Name Type Description Default
key str

Property key

required
value Any

Property value

required

Returns:

Type Description
str

Formatted string for display

Source code in src/mineral_database/models.py
def format_property_value(key: str, value: Any) -> str:
    """Format a property value for display.

    Args:
        key: Property key
        value: Property value

    Returns:
        Formatted string for display
    """
    if value is None:
        return "None"
    if isinstance(value, list):
        if len(value) <= 3:
            return ", ".join(str(v) for v in value)
        return ", ".join(str(v) for v in value[:3]) + "..."
    if isinstance(value, tuple):
        return "-".join(str(v) for v in value)
    if isinstance(value, float):
        return f"{value:.3f}".rstrip("0").rstrip(".")
    return str(value)

Pre-generated Models

Functions for accessing pre-generated 3D visualizations stored in the database.

get_model_svg

Get pre-generated SVG visualization.

from mineral_database import get_model_svg

svg = get_model_svg('diamond')
if svg:
    with open('diamond.svg', 'w') as f:
        f.write(svg)

mineral_database.get_model_svg(mineral_id)

Get the pre-generated SVG for a mineral.

Parameters:

Name Type Description Default
mineral_id str

Mineral preset ID (case-insensitive)

required

Returns:

Type Description
str | None

SVG markup string or None if not generated

Source code in src/mineral_database/queries.py
def get_model_svg(mineral_id: str) -> str | None:
    """Get the pre-generated SVG for a mineral.

    Args:
        mineral_id: Mineral preset ID (case-insensitive)

    Returns:
        SVG markup string or None if not generated
    """
    with get_connection(_db_path) as conn:
        models = get_mineral_models(conn, mineral_id)
        value = models.get("model_svg")
        return str(value) if value is not None else None

get_model_stl

Get pre-generated binary STL for 3D printing.

from mineral_database import get_model_stl

stl = get_model_stl('quartz')
if stl:
    with open('quartz.stl', 'wb') as f:
        f.write(stl)

mineral_database.get_model_stl(mineral_id)

Get the pre-generated STL binary for a mineral.

Parameters:

Name Type Description Default
mineral_id str

Mineral preset ID (case-insensitive)

required

Returns:

Type Description
bytes | None

Binary STL data or None if not generated

Source code in src/mineral_database/queries.py
def get_model_stl(mineral_id: str) -> bytes | None:
    """Get the pre-generated STL binary for a mineral.

    Args:
        mineral_id: Mineral preset ID (case-insensitive)

    Returns:
        Binary STL data or None if not generated
    """
    with get_connection(_db_path) as conn:
        models = get_mineral_models(conn, mineral_id)
        value = models.get("model_stl")
        if isinstance(value, bytes):
            return value
        return None

get_model_gltf

Get pre-generated glTF for web display.

from mineral_database import get_model_gltf
import json

gltf = get_model_gltf('ruby')
if gltf:
    with open('ruby.gltf', 'w') as f:
        json.dump(gltf, f)

mineral_database.get_model_gltf(mineral_id)

Get the pre-generated glTF for a mineral.

Parameters:

Name Type Description Default
mineral_id str

Mineral preset ID (case-insensitive)

required

Returns:

Type Description
dict[str, object] | None

glTF dictionary or None if not generated

Source code in src/mineral_database/queries.py
def get_model_gltf(mineral_id: str) -> dict[str, object] | None:
    """Get the pre-generated glTF for a mineral.

    Args:
        mineral_id: Mineral preset ID (case-insensitive)

    Returns:
        glTF dictionary or None if not generated
    """
    import json

    with get_connection(_db_path) as conn:
        models = get_mineral_models(conn, mineral_id)
        gltf_str = models.get("model_gltf")
        if gltf_str and isinstance(gltf_str, str):
            result: dict[str, object] = json.loads(gltf_str)
            return result
        return None

get_models_generated_at

Check when models were generated.

from mineral_database import get_models_generated_at

timestamp = get_models_generated_at('emerald')
# Returns ISO timestamp or None

mineral_database.get_models_generated_at(mineral_id)

Get the timestamp when models were generated for a mineral.

Parameters:

Name Type Description Default
mineral_id str

Mineral preset ID (case-insensitive)

required

Returns:

Type Description
str | None

ISO timestamp string or None if not generated

Source code in src/mineral_database/queries.py
def get_models_generated_at(mineral_id: str) -> str | None:
    """Get the timestamp when models were generated for a mineral.

    Args:
        mineral_id: Mineral preset ID (case-insensitive)

    Returns:
        ISO timestamp string or None if not generated
    """
    with get_connection(_db_path) as conn:
        models = get_mineral_models(conn, mineral_id)
        value = models.get("models_generated_at")
        return str(value) if value is not None else None

Backwards Compatibility

CRYSTAL_PRESETS

Dict-like interface for legacy code migration.

from mineral_database import CRYSTAL_PRESETS

# Supports all dict operations
preset = CRYSTAL_PRESETS['diamond']
preset = CRYSTAL_PRESETS.get('ruby', None)
'garnet' in CRYSTAL_PRESETS
len(CRYSTAL_PRESETS)
list(CRYSTAL_PRESETS.keys())
list(CRYSTAL_PRESETS.values())
list(CRYSTAL_PRESETS.items())

mineral_database.CRYSTAL_PRESETS = PresetDict() module-attribute