Home Information - Your home, your data, organized.
Python
Feature/82 Implement Media Thumbnail Previews for File Attributes (#267)
Thiago Trautwein Santose2c0867cb052
diff --git a/.github/workflows/django-tests.yml b/.github/workflows/django-tests.ymlindex 21646d8e..9e2a1c0f 100644--- a/.github/workflows/django-tests.yml+++ b/.github/workflows/django-tests.yml@@ -38,6 +38,11 @@ jobs:with:python-version: '3.11'+ - name: Install System Dependencies+ run: |+ sudo apt-get update+ sudo apt-get install -y poppler-utils+- name: Install Dependenciesrun: |python -m pip install --upgrade pipdiff --git a/Dockerfile b/Dockerfileindex de36775c..b6efdbdb 100644--- a/Dockerfile+++ b/Dockerfile@@ -9,6 +9,7 @@ RUN apt-get update \nginx \redis-server \redis-tools \+ poppler-utils \&& mkdir -p /var/log/supervisor \&& mkdir -p /etc/supervisor/conf.d \&& rm -rf /var/lib/apt/lists/* \diff --git a/docs/dev/Dependencies.md b/docs/dev/Dependencies.mdindex 16aca494..64f7b03e 100644--- a/docs/dev/Dependencies.md+++ b/docs/dev/Dependencies.md@@ -119,3 +119,22 @@ mkdir ~/.redistouch ~/.redis/redis.conf```Then run with `redis-server`.++### Poppler++_Optional. Required for PDF thumbnail previews on file attributes. Without it, PDF attributes still upload and work — they just display a generic icon instead of a rendered preview._++The `pdf2image` Python package (installed via requirements) shells out to `pdftoppm` from the `poppler-utils` system package. Docker builds install this automatically; local development needs it installed separately.++#### MacOS++``` shell+brew install poppler+```++#### Ubuntu (GNU/Linux)++``` shell+sudo apt install poppler-utils+```+diff --git a/docs/dev/Setup.md b/docs/dev/Setup.mdindex 8452ff65..381dd70e 100644--- a/docs/dev/Setup.md+++ b/docs/dev/Setup.md@@ -147,7 +147,7 @@ cd $PROJ_DIR/src### Running-Ensure that a local Redis server is running (see the Dependencies page for installation instructions). Note: Redis is only a manual dependency for local development — Docker deployments bundle it automatically. Then:+Ensure that a local Redis server is running (see the [Dependencies page](Dependencies.md) for installation instructions). Note: Redis is only a manual dependency for local development — Docker deployments bundle it automatically. Then:``` shellcd $PROJ_DIR/srcdiff --git a/src/hi/apps/attribute/forms.py b/src/hi/apps/attribute/forms.pyindex 576e7b64..dc581532 100644--- a/src/hi/apps/attribute/forms.py+++ b/src/hi/apps/attribute/forms.py@@ -6,6 +6,7 @@ from django import formsfrom hi.apps.common.utils import is_blank, str_to_boolfrom .enums import AttributeType, AttributeValueType+from .thumbnail import AttributeThumbnailclass RegularAttributeBaseFormSet(forms.BaseInlineFormSet):@@ -179,10 +180,15 @@ class AttributeUploadForm( forms.ModelForm ):def save( self, commit = True ):instance = super().save( commit = False )- mime_type_tuple = mimetypes.guess_type( instance.file_value.name )+ uploaded_mime_type = getattr(instance.file_value, 'content_type', None)+ if uploaded_mime_type:+ uploaded_mime_type = uploaded_mime_type.split(';', 1)[0].strip().lower()+ if not uploaded_mime_type:+ mime_type_tuple = mimetypes.guess_type( instance.file_value.name )+ uploaded_mime_type = mime_type_tuple[0]instance.name = instance.file_value.name- instance.file_mime_type = mime_type_tuple[0]+ instance.file_mime_type = uploaded_mime_typeinstance.value_type_str = str( AttributeValueType.FILE )instance.attribute_type_str = str(AttributeType.CUSTOM)instance.is_editable = True@@ -190,4 +196,6 @@ class AttributeUploadForm( forms.ModelForm ):if commit:instance.save()+ thumbnail_generated = AttributeThumbnail(instance).generate_thumbnail_best_effort()+ instance.set_thumbnail_exists_cache(thumbnail_generated)return instancediff --git a/src/hi/apps/attribute/management/commands/backfill_attribute_thumbnails.py b/src/hi/apps/attribute/management/commands/backfill_attribute_thumbnails.pynew file mode 100644index 00000000..b839a30e--- /dev/null+++ b/src/hi/apps/attribute/management/commands/backfill_attribute_thumbnails.py@@ -0,0 +1,80 @@+from django.core.management.base import BaseCommand++from hi.apps.entity.models import EntityAttribute+from hi.apps.location.models import LocationAttribute+from hi.apps.attribute.enums import AttributeValueType+from hi.apps.attribute.thumbnail import AttributeThumbnail+++class Command(BaseCommand):+ help = 'Backfill missing thumbnails for existing file attributes.'++ def add_arguments(self, parser):+ parser.add_argument(+ '--dry-run',+ action='store_true',+ help='Show what would be generated without writing files.',+ )++ def handle(self, *args, **options):+ dry_run = bool(options['dry_run'])++ scanned = 0+ supported = 0+ unsupported = 0+ skipped_existing = 0+ generated = 0+ failed = 0+ would_generate = 0++ model_classes = [EntityAttribute, LocationAttribute]+ self.stdout.write('Processing models: EntityAttribute, LocationAttribute')++ for model_class in model_classes:+ queryset = model_class.objects.filter(+ value_type_str=str(AttributeValueType.FILE),+ ).exclude(file_value__isnull=True).exclude(file_value='').order_by('id')++ for attribute in queryset.iterator():+ scanned += 1++ thumbnail_path = attribute.thumbnail_relative_path+ if not thumbnail_path:+ unsupported += 1+ continue++ supported += 1++ if attribute.has_thumbnail:+ skipped_existing += 1+ continue++ if dry_run:+ would_generate += 1+ continue++ was_generated = AttributeThumbnail(attribute).generate_thumbnail_best_effort()+ attribute.set_thumbnail_exists_cache(was_generated)+ if was_generated:+ generated += 1+ else:+ failed += 1++ summary = (+ 'Thumbnail backfill summary: '+ f'scanned={scanned}, '+ f'supported={supported}, '+ f'unsupported={unsupported}, '+ f'skipped_existing={skipped_existing}, '+ f'generated={generated}, '+ f'failed={failed}, '+ f'would_generate={would_generate}'+ )++ if dry_run:+ self.stdout.write(self.style.WARNING('Dry-run mode enabled. No files were written.'))++ if failed:+ self.stdout.write(self.style.WARNING(summary))+ else:+ self.stdout.write(self.style.SUCCESS(summary))\ No newline at end of filediff --git a/src/hi/apps/attribute/models.py b/src/hi/apps/attribute/models.pyindex 9c6bf1f5..d7cb3c93 100644--- a/src/hi/apps/attribute/models.py+++ b/src/hi/apps/attribute/models.py@@ -14,6 +14,7 @@ from .enums import (AttributeType,)from .managers import ActiveAttributeManager, DeletedAttributeManager+from .thumbnail import AttributeThumbnail, AttributeThumbnailRuleslogger = logging.getLogger(__name__)@@ -154,6 +155,72 @@ class AttributeModel(models.Model):passreturn dict()+ @property+ def supports_thumbnail_generation(self):+ return AttributeThumbnailRules.supports_thumbnail_generation(+ file_value=self.file_value,+ file_mime_type=self.file_mime_type,+ )++ @property+ def thumbnail_relative_path(self):+ return AttributeThumbnailRules.thumbnail_relative_path(+ file_value=self.file_value,+ file_mime_type=self.file_mime_type,+ )++ def _thumbnail_exists(self):+ if hasattr(self, '_thumbnail_exists_cache'):+ return self._thumbnail_exists_cache++ thumbnail_path = self.thumbnail_relative_path+ self._thumbnail_exists_cache = bool( thumbnail_path and default_storage.exists(thumbnail_path) )+ return self._thumbnail_exists_cache++ def set_thumbnail_exists_cache(self, exists):+ self._thumbnail_exists_cache = bool(exists)+ return self._thumbnail_exists_cache++ def clear_thumbnail_exists_cache(self):+ if hasattr(self, '_thumbnail_exists_cache'):+ del self._thumbnail_exists_cache+ return++ @property+ def has_thumbnail(self):+ return self._thumbnail_exists()++ def ensure_thumbnail(self):+ """Generate a thumbnail synchronously if one is missing for this+ file attribute. Intended as a lazy-generation hook invoked from+ display templates via the ``{% ensure_thumbnail %}`` tag.++ Spreads thumbnail-generation cost across actual usage (each file+ attribute pays once, on first view) instead of forcing an upfront+ pass at startup. No-op for unsupported file types or already-+ generated thumbnails. Generation failures are swallowed by the+ best-effort helper; the template falls back to its icon+ placeholder in that case."""+ if not self.supports_thumbnail_generation:+ return+ if self._thumbnail_exists():+ return+ AttributeThumbnail( self ).generate_thumbnail_best_effort()+ self.clear_thumbnail_exists_cache()+ return++ @property+ def thumbnail_url(self):+ if not self._thumbnail_exists():+ return None+ return default_storage.url(self.thumbnail_relative_path)++ @property+ def preview_state(self):+ if self.has_thumbnail:+ return 'thumbnail'+ return 'placeholder'+def save(self, *args, **kwargs):# Skip history tracking for kwargs that disable ittrack_history = kwargs.pop('track_history', True)@@ -201,6 +268,8 @@ class AttributeModel(models.Model):def delete( self, *args, **kwargs ):""" Deleting file from MEDIA_ROOT on best effort basis. Ignore if fails. """+ thumbnail_path = self.thumbnail_relative_path+if self.file_value:try:if default_storage.exists( self.file_value.name ):@@ -212,6 +281,16 @@ class AttributeModel(models.Model):# Log the error or handle it accordinglylogger.warn( f'Error deleting Attribute file {self.file_value.name}: {e}' )+ if thumbnail_path:+ try:+ if default_storage.exists(thumbnail_path):+ default_storage.delete(thumbnail_path)+ logger.debug(f'Deleted Attribute thumbnail: {thumbnail_path}')+ except Exception as e:+ logger.warn(f'Error deleting Attribute thumbnail {thumbnail_path}: {e}')++ self.set_thumbnail_exists_cache(False)+super().delete( *args, **kwargs )returndiff --git a/src/hi/apps/attribute/templates/attribute/components/file_card.html b/src/hi/apps/attribute/templates/attribute/components/file_card.htmlindex 26522088..c880b682 100644--- a/src/hi/apps/attribute/templates/attribute/components/file_card.html+++ b/src/hi/apps/attribute/templates/attribute/components/file_card.html@@ -4,11 +4,20 @@ V2 File Card ComponentIndividual file attribute card with preview, actions, and metadata{% endcomment %}-<div class="{{ DIVID.ATTR_V2_FILE_CARD_CLASS }}"- data-attribute-id="{{ attribute.id }}"+{% comment %}+Lazy thumbnail generation: triggers synchronous generation on first+view for any supported file attribute that doesn't yet have one.+Render-time hook with no output — see ``ensure_thumbnail`` template+tag in attribute_extras.py.+{% endcomment %}+{% ensure_thumbnail attribute %}++<div class="{{ DIVID.ATTR_V2_FILE_CARD_CLASS }}"+ data-attribute-id="{{ attribute.id }}"data-url-detect="true"data-order-index="{{ forloop.counter }}"- data-thumbnail-ready="true"+ data-thumbnail-ready="{{ attribute.has_thumbnail|yesno:'true,false' }}"+ data-preview-state="{{ attribute.preview_state }}"data-mime-type="{{ attribute.file_mime_type|default:'unknown' }}"data-file-size="{{ attribute.file_value.size|default:0 }}">@@ -19,25 +28,33 @@ Individual file attribute card with preview, actions, and metadatadata-attribute-id="{{ attribute.id }}"><!-- File Preview/Thumbnail Area -->- <div class="attr-v2-file-thumbnail"+ <div class="attr-v2-file-thumbnail{% if attribute.has_thumbnail %} has-thumbnail{% endif %}{% if attribute.file_mime_type == 'application/pdf' %} is-document{% endif %}"onclick="window.open('{{ attribute.file_value.url }}', '_blank');"title="Tap to view file">- {% comment %}Content-type specific placeholder icons{% endcomment %}- {% if attribute.file_mime_type|slice:':5' == "image" %}- {% icon "camera" size="lg" %}- <div class="attr-v2-file-type-label">IMAGE</div>- {% elif attribute.file_mime_type == "application/pdf" %}- {% icon "upload" size="lg" %}- <div class="attr-v2-file-type-label">PDF</div>- {% elif attribute.file_mime_type|slice:':4' == "text" %}- {% icon "edit" size="lg" %}- <div class="attr-v2-file-type-label">TEXT</div>- {% elif attribute.file_mime_type|slice:':5' == "video" %}- {% icon "video" size="lg" %}- <div class="attr-v2-file-type-label">VIDEO</div>+ {% if attribute.has_thumbnail and attribute.thumbnail_url %}+ <img src="{{ attribute.thumbnail_url }}"+ alt="Preview for {{ attribute.value|default:attribute.name }}"+ class="attr-v2-file-thumbnail-image"+ loading="lazy"+ decoding="async">{% else %}- {% icon "upload" size="lg" %}- <div class="attr-v2-file-type-label">FILE</div>+ {% comment %}Content-type specific placeholder icons{% endcomment %}+ {% if attribute.file_mime_type|slice:':5' == "image" %}+ {% icon "camera" size="lg" %}+ <div class="attr-v2-file-type-label">IMAGE</div>+ {% elif attribute.file_mime_type == "application/pdf" %}+ {% icon "upload" size="lg" %}+ <div class="attr-v2-file-type-label">PDF</div>+ {% elif attribute.file_mime_type|slice:':4' == "text" %}+ {% icon "edit" size="lg" %}+ <div class="attr-v2-file-type-label">TEXT</div>+ {% elif attribute.file_mime_type|slice:':5' == "video" %}+ {% icon "video" size="lg" %}+ <div class="attr-v2-file-type-label">VIDEO</div>+ {% else %}+ {% icon "upload" size="lg" %}+ <div class="attr-v2-file-type-label">FILE</div>+ {% endif %}{% endif %}<!-- Reorder Controls (overlay in upper right) -->diff --git a/src/hi/apps/attribute/templatetags/attribute_extras.py b/src/hi/apps/attribute/templatetags/attribute_extras.pyindex 50f74305..cad883a0 100644--- a/src/hi/apps/attribute/templatetags/attribute_extras.py+++ b/src/hi/apps/attribute/templatetags/attribute_extras.py@@ -316,3 +316,19 @@ def attribute_text_linkify(value):html = ''.join(str(part) for part in rendered_parts).replace('\n', '<br>')return mark_safe(html)+++def ensure_thumbnail(attribute):+ """Render-time hook that triggers lazy thumbnail generation for a+ file attribute if one isn't already present. Use in display+ templates as ``{% ensure_thumbnail attribute %}`` ahead of any+ ``attribute.has_thumbnail`` / ``attribute.thumbnail_url`` reads.++ Renders nothing (the tag's side effect is the work). No-op for+ attributes that don't support thumbnails or already have one;+ generation failures are swallowed and the surrounding template+ falls back to its placeholder."""+ if hasattr( attribute, 'ensure_thumbnail' ):+ attribute.ensure_thumbnail()+ return ''diff --git a/src/hi/apps/attribute/tests/test_models.py b/src/hi/apps/attribute/tests/test_models.pyindex 6fbfc144..435bf004 100644--- a/src/hi/apps/attribute/tests/test_models.py+++ b/src/hi/apps/attribute/tests/test_models.py@@ -1,10 +1,17 @@import jsonimport loggingimport uuid-from unittest.mock import patch+from io import BytesIO+from unittest.mock import patch, call++from django.core.files.base import ContentFile+from django.core.files.storage import default_storage++from PIL import Imagefrom hi.apps.attribute.models import AttributeModelfrom hi.apps.attribute.enums import AttributeValueType, AttributeType+from hi.apps.attribute.thumbnail import AttributeThumbnailfrom hi.apps.entity.enums import EntityTypefrom hi.apps.entity.models import Entity, EntityAttributefrom hi.integrations.transient_models import IntegrationKey@@ -22,6 +29,23 @@ class ConcreteAttributeModel(AttributeModel):class TestAttributeModel(BaseTestCase):+ @staticmethod+ def _create_valid_png_image_bytes(size=(128, 96)):+ image = Image.new('RGB', size=size, color=(24, 120, 220))+ image_bytes = BytesIO()+ image.save(image_bytes, format='PNG')+ return image_bytes.getvalue()++ @staticmethod+ def _create_valid_pdf_bytes():+ try:+ image = Image.new('RGB', size=(360, 220), color=(255, 255, 255))+ pdf_bytes = BytesIO()+ image.save(pdf_bytes, format='PDF')+ return pdf_bytes.getvalue()+ except Exception:+ return None+def test_attribute_model_enum_property_conversions(self):"""Test enum property conversions - custom business logic."""attr = ConcreteAttributeModel(@@ -149,6 +173,233 @@ class TestAttributeModel(BaseTestCase):self.assertEqual(attr.file_value.field.upload_to, 'test_attributes/')return+ def test_thumbnail_relative_path_for_supported_image_file(self):+ """Test deterministic thumbnail path generation for supported image files."""+ attr = ConcreteAttributeModel(+ name='photo',+ value_type_str='FILE',+ attribute_type_str='CUSTOM',+ file_mime_type='image/jpeg'+ )+ attr.file_value = 'entity/attributes/front_door.jpg'++ self.assertTrue(attr.supports_thumbnail_generation)+ self.assertEqual(+ attr.thumbnail_relative_path,+ 'entity/attributes/thumbnails/front_door.thumb.png'+ )+ return++ def test_thumbnail_relative_path_none_for_unsupported_file_type(self):+ """Test unsupported files do not produce thumbnail paths."""+ attr = ConcreteAttributeModel(+ name='document',+ value_type_str='FILE',+ attribute_type_str='CUSTOM',+ file_mime_type='text/plain'+ )+ attr.file_value = 'entity/attributes/manual.txt'++ self.assertFalse(attr.supports_thumbnail_generation)+ self.assertIsNone(attr.thumbnail_relative_path)+ return++ def test_thumbnail_relative_path_for_supported_pdf_file(self):+ """Test deterministic thumbnail path generation for supported PDF files."""+ attr = ConcreteAttributeModel(+ name='manual',+ value_type_str='FILE',+ attribute_type_str='CUSTOM',+ file_mime_type='application/pdf'+ )+ attr.file_value = 'entity/attributes/manual.pdf'++ self.assertTrue(attr.supports_thumbnail_generation)+ self.assertEqual(+ attr.thumbnail_relative_path,+ 'entity/attributes/thumbnails/manual.thumb.png'+ )+ return++ def test_generate_thumbnail_best_effort_success(self):+ """Test thumbnail generation creates a derived file for valid image content."""+ with self.isolated_media_root():+ source_path = 'test_attributes/camera_snapshot.png'+ default_storage.save(+ source_path,+ ContentFile(self._create_valid_png_image_bytes(size=(900, 600)))+ )++ attr = ConcreteAttributeModel(+ name='camera_snapshot',+ value_type_str='FILE',+ attribute_type_str='CUSTOM',+ file_mime_type='image/png'+ )+ attr.file_value = source_path++ generated = AttributeThumbnail(attr).generate_thumbnail_best_effort()++ self.assertTrue(generated)+ self.assertTrue(default_storage.exists(attr.thumbnail_relative_path))+ self.assertTrue(attr.has_thumbnail)+ self.assertIsNotNone(attr.thumbnail_url)+ self.assertIn('test_attributes/thumbnails/camera_snapshot.thumb.png', attr.thumbnail_url)+ return++ def test_generate_thumbnail_best_effort_invalid_image_content(self):+ """Test thumbnail generation failure is graceful for bad image bytes."""+ with self.isolated_media_root():+ source_path = 'test_attributes/not_really_an_image.jpg'+ default_storage.save(source_path, ContentFile(b'plain text bytes, not an image'))++ attr = ConcreteAttributeModel(+ name='broken_image',+ value_type_str='FILE',+ attribute_type_str='CUSTOM',+ file_mime_type='image/jpeg'+ )+ attr.file_value = source_path++ generated = AttributeThumbnail(attr).generate_thumbnail_best_effort()++ self.assertFalse(generated)+ self.assertFalse(attr.has_thumbnail)+ self.assertIsNone(attr.thumbnail_url)+ return++ def test_generate_thumbnail_best_effort_pdf_success(self):+ """Test thumbnail generation from first page of a PDF file."""+ pdf_bytes = self._create_valid_pdf_bytes()+ if not pdf_bytes:+ self.skipTest('Unable to generate test PDF bytes in this environment')++ with self.isolated_media_root():+ source_path = 'test_attributes/manual.pdf'+ default_storage.save(source_path, ContentFile(pdf_bytes))++ attr = ConcreteAttributeModel(+ name='manual',+ value_type_str='FILE',+ attribute_type_str='CUSTOM',+ file_mime_type='application/pdf'+ )+ attr.file_value = source_path++ generated = AttributeThumbnail(attr).generate_thumbnail_best_effort()++ self.assertTrue(generated)+ self.assertTrue(default_storage.exists(attr.thumbnail_relative_path))+ self.assertTrue(attr.has_thumbnail)+ self.assertIsNotNone(attr.thumbnail_url)+ return++ def test_ensure_thumbnail_generates_when_missing(self):+ """ensure_thumbnail() lazily produces a thumbnail on first call when+ the source is supported and no thumbnail is present yet."""+ with self.isolated_media_root():+ source_path = 'test_attributes/lazy_view.png'+ default_storage.save(+ source_path,+ ContentFile(self._create_valid_png_image_bytes()),+ )++ attr = ConcreteAttributeModel(+ name='lazy_view',+ value_type_str='FILE',+ attribute_type_str='CUSTOM',+ file_mime_type='image/png',+ )+ attr.file_value = source_path++ self.assertFalse(attr.has_thumbnail)++ attr.ensure_thumbnail()++ self.assertTrue(default_storage.exists(attr.thumbnail_relative_path))+ self.assertTrue(attr.has_thumbnail)+ return++ @patch('hi.apps.attribute.models.AttributeThumbnail')+ def test_ensure_thumbnail_noop_when_already_present(self, mock_thumbnail_cls):+ """ensure_thumbnail() must NOT re-trigger generation when a thumbnail+ already exists on disk — the per-render cost should be one+ storage.exists() check."""+ with self.isolated_media_root():+ source_path = 'test_attributes/already_done.png'+ default_storage.save(+ source_path,+ ContentFile(self._create_valid_png_image_bytes()),+ )++ attr = ConcreteAttributeModel(+ name='already_done',+ value_type_str='FILE',+ attribute_type_str='CUSTOM',+ file_mime_type='image/png',+ )+ attr.file_value = source_path++ # Pre-populate the thumbnail file directly so the model sees+ # an existing thumbnail without invoking the generator.+ default_storage.save(+ attr.thumbnail_relative_path,+ ContentFile(b'pre-existing thumbnail bytes'),+ )++ attr.ensure_thumbnail()++ mock_thumbnail_cls.assert_not_called()+ return++ def test_ensure_thumbnail_noop_for_unsupported_mime_type(self):+ """ensure_thumbnail() short-circuits for file types outside the+ supported set — no generation attempt, no thumbnail produced."""+ with self.isolated_media_root():+ source_path = 'test_attributes/notes.txt'+ default_storage.save(source_path, ContentFile(b'plain text notes'))++ attr = ConcreteAttributeModel(+ name='notes',+ value_type_str='FILE',+ attribute_type_str='CUSTOM',+ file_mime_type='text/plain',+ )+ attr.file_value = source_path++ with patch(+ 'hi.apps.attribute.models.AttributeThumbnail'+ ) as mock_thumbnail_cls:+ attr.ensure_thumbnail()+ mock_thumbnail_cls.assert_not_called()++ self.assertFalse(attr.has_thumbnail)+ self.assertIsNone(attr.thumbnail_relative_path)+ return++ @patch('hi.apps.attribute.models.default_storage')+ def test_attribute_model_file_delete_also_deletes_thumbnail(self, mock_storage):+ """Test file deletion removes generated thumbnail when present."""+ mock_storage.exists.side_effect = [True, True]++ attr = ConcreteAttributeModel(+ name='test_attr',+ value_type_str='FILE',+ attribute_type_str='CUSTOM',+ file_mime_type='image/jpeg'+ )+ attr.file_value = 'test_image.jpg'+ attr.pk = 1++ with patch('django.db.models.Model.delete'):+ attr.delete()++ self.assertEqual(+ mock_storage.delete.call_args_list,+ [call('test_image.jpg'), call('thumbnails/test_image.thumb.png')]+ )+ return+@patch('hi.apps.attribute.models.default_storage')def test_attribute_model_file_deletion_missing_file(self, mock_storage):"""Test file deletion when file doesn't exist - error handling."""diff --git a/src/hi/apps/attribute/tests/test_thumbnail_command.py b/src/hi/apps/attribute/tests/test_thumbnail_command.pynew file mode 100644index 00000000..cdb33c1f--- /dev/null+++ b/src/hi/apps/attribute/tests/test_thumbnail_command.py@@ -0,0 +1,83 @@+from io import BytesIO, StringIO++from django.core.files.base import ContentFile+from django.core.management import call_command+from django.core.files.storage import default_storage++from PIL import Image++from hi.apps.entity.enums import EntityType+from hi.testing.base_test_case import BaseTestCase+from hi.apps.entity.models import Entity, EntityAttribute+from hi.apps.attribute.enums import AttributeType, AttributeValueType+++class TestBackfillAttributeThumbnailsCommand(BaseTestCase):++ @staticmethod+ def _create_valid_png_image_bytes(size=(320, 240)):+ image = Image.new('RGB', size=size, color=(80, 120, 200))+ image_bytes = BytesIO()+ image.save(image_bytes, format='PNG')+ return image_bytes.getvalue()++ def _create_entity(self):+ return Entity.objects.create(+ name='Thumbnail Command Test Entity',+ integration_id='test.thumbnail.command.entity',+ integration_name='test_integration',+ entity_type_str=str(EntityType.LIGHT),+ )++ def test_command_generates_thumbnails_for_existing_file_attributes(self):+ with self.isolated_media_root():+ # Pass the file contents to ``file_value`` directly so+ # ``AttributeModel.save()`` owns filename generation —+ # otherwise the model's ``generate_unique_filename()``+ # timestamp suffix desyncs the attribute's stored path+ # from the on-disk path written by ``default_storage.save()``.+ entity = self._create_entity()+ attribute = EntityAttribute.objects.create(+ entity=entity,+ name='retroactive_image',+ value='Retroactive image',+ file_value=ContentFile(+ self._create_valid_png_image_bytes(),+ name='retroactive-image.png',+ ),+ file_mime_type='image/png',+ value_type_str=str(AttributeValueType.FILE),+ attribute_type_str=str(AttributeType.CUSTOM),+ )++ self.assertFalse(default_storage.exists(attribute.thumbnail_relative_path))++ stdout = StringIO()+ call_command('backfill_attribute_thumbnails', stdout=stdout)++ self.assertTrue(default_storage.exists(attribute.thumbnail_relative_path))+ self.assertIn('generated=1', stdout.getvalue())++ def test_command_dry_run_does_not_write_thumbnail_files(self):+ with self.isolated_media_root():+ entity = self._create_entity()+ attribute = EntityAttribute.objects.create(+ entity=entity,+ name='retroactive_image_dry_run',+ value='Retroactive image dry-run',+ file_value=ContentFile(+ self._create_valid_png_image_bytes(),+ name='retroactive-image-dry-run.png',+ ),+ file_mime_type='image/png',+ value_type_str=str(AttributeValueType.FILE),+ attribute_type_str=str(AttributeType.CUSTOM),+ )++ self.assertFalse(default_storage.exists(attribute.thumbnail_relative_path))++ stdout = StringIO()+ call_command('backfill_attribute_thumbnails', '--dry-run', stdout=stdout)++ self.assertFalse(default_storage.exists(attribute.thumbnail_relative_path))+ self.assertIn('would_generate=1', stdout.getvalue())\ No newline at end of filediff --git a/src/hi/apps/attribute/thumbnail.py b/src/hi/apps/attribute/thumbnail.pynew file mode 100644index 00000000..6a67677e--- /dev/null+++ b/src/hi/apps/attribute/thumbnail.py@@ -0,0 +1,195 @@+import logging+import mimetypes+from io import BytesIO+from pathlib import PurePosixPath+from typing import TYPE_CHECKING++from django.core.files.base import ContentFile+from django.core.files.storage import default_storage++if TYPE_CHECKING:+ from .models import AttributeModel++logger = logging.getLogger(__name__)+++class AttributeThumbnailRules:++ THUMBNAIL_SUBDIRECTORY = 'thumbnails'+ THUMBNAIL_SUFFIX = '.thumb.png'+ THUMBNAIL_IMAGE_MIME_TYPES = {+ 'image/jpeg',+ 'image/png',+ 'image/webp',+ 'image/gif',+ }+ THUMBNAIL_PDF_MIME_TYPES = {+ 'application/pdf',+ }+ THUMBNAIL_SUPPORTED_MIME_TYPES = THUMBNAIL_IMAGE_MIME_TYPES | THUMBNAIL_PDF_MIME_TYPES++ @classmethod+ def effective_file_mime_type(cls, file_value, file_mime_type):+ if file_mime_type:+ mime_type = file_mime_type.split(';', 1)[0].strip().lower()+ if mime_type:+ return mime_type++ if file_value and file_value.name:+ guessed_mime_type, _ = mimetypes.guess_type(file_value.name)+ if guessed_mime_type:+ return guessed_mime_type.strip().lower()+ return None++ @classmethod+ def supports_thumbnail_generation(cls, file_value, file_mime_type):+ if not file_value or not file_value.name:+ return False++ mime_type = cls.effective_file_mime_type(+ file_value=file_value,+ file_mime_type=file_mime_type,+ )+ return bool(mime_type and mime_type in cls.THUMBNAIL_SUPPORTED_MIME_TYPES)++ @classmethod+ def thumbnail_relative_path(cls, file_value, file_mime_type):+ if not cls.supports_thumbnail_generation( file_value = file_value, file_mime_type = file_mime_type ):+ return None++ source_path = PurePosixPath(file_value.name)+ thumbnail_name = f'{source_path.stem}{cls.THUMBNAIL_SUFFIX}'+ if str(source_path.parent) == '.':+ return str(PurePosixPath(cls.THUMBNAIL_SUBDIRECTORY) / thumbnail_name)+ return str(source_path.parent / cls.THUMBNAIL_SUBDIRECTORY / thumbnail_name)+++class AttributeThumbnail:++ THUMBNAIL_SIZE = (320, 320)++ # Per-mime-type input size caps. PDFs get a tighter ceiling because+ # rendering cost scales with page dimensions and complexity, not+ # raw byte count — a small but pathological PDF can still be much+ # more expensive than a moderately sized image.+ THUMBNAIL_MAX_SOURCE_BYTES = 20 * 1024 * 1024+ THUMBNAIL_MAX_PDF_SOURCE_BYTES = 10 * 1024 * 1024++ # Bounds on PDF rendering. ``PDF_RENDER_SIZE`` caps the rasterized+ # output dimensions before the thumbnail resize, preventing a+ # large-page PDF from producing a multi-GB pixel buffer at+ # pdf2image's 200-DPI default. ``PDF_RENDER_TIMEOUT_SECS`` is+ # threaded through to the underlying pdftoppm subprocess so a+ # crafted PDF can't hang generation indefinitely.+ PDF_RENDER_SIZE = (640, 640)+ PDF_RENDER_TIMEOUT_SECS = 30++ def __init__(self, attribute: 'AttributeModel'):+ self.attribute = attribute++ def _max_source_bytes_for_mime_type(self, mime_type):+ if mime_type in AttributeThumbnailRules.THUMBNAIL_PDF_MIME_TYPES:+ return self.THUMBNAIL_MAX_PDF_SOURCE_BYTES+ return self.THUMBNAIL_MAX_SOURCE_BYTES++ def _render_pdf_first_page_image(self, file_handle):+ try:+ from pdf2image import convert_from_bytes+ except Exception as e:+ logger.warning( f'pdf2image unavailable for PDF thumbnail generation: {e}' )+ return None++ try:+ pdf_bytes = file_handle.read()+ rendered_pages = convert_from_bytes(+ pdf_bytes,+ first_page = 1,+ last_page = 1,+ size = self.PDF_RENDER_SIZE,+ timeout = self.PDF_RENDER_TIMEOUT_SECS,+ )+ if not rendered_pages:+ logger.warning( f'Cannot generate thumbnail for empty PDF: {self.attribute.file_value.name}' )+ return None+ return rendered_pages[0]++ except Exception as e:+ logger.warning( f'Error rendering PDF thumbnail for {self.attribute.file_value.name}: {e}' )+ return None++ def _load_source_image_for_thumbnail(self, file_handle, mime_type, image_module, image_ops_module):+ if mime_type in AttributeThumbnailRules.THUMBNAIL_PDF_MIME_TYPES:+ return self._render_pdf_first_page_image(file_handle=file_handle)++ with image_module.open(file_handle) as img:+ processed_img = image_ops_module.exif_transpose(img)+ return processed_img.copy()++ def generate_thumbnail_best_effort(self, force=False):+ thumbnail_path = self.attribute.thumbnail_relative_path+ if not thumbnail_path:+ return False++ mime_type = AttributeThumbnailRules.effective_file_mime_type(+ file_value=self.attribute.file_value,+ file_mime_type=self.attribute.file_mime_type,+ )++ if not force and default_storage.exists(thumbnail_path):+ return True++ if self.attribute.file_value and getattr(self.attribute.file_value, 'size', None):+ max_source_bytes = self._max_source_bytes_for_mime_type( mime_type )+ if self.attribute.file_value.size > max_source_bytes:+ logger.info(+ f'Skipping thumbnail generation for {self.attribute.file_value.name}: '+ f'file too large ({self.attribute.file_value.size} bytes, '+ f'limit {max_source_bytes} bytes for {mime_type})'+ )+ return False++ try:+ from PIL import Image, ImageOps, UnidentifiedImageError+ except Exception as e:+ logger.warning( f'Pillow unavailable for thumbnail generation: {e}' )+ return False++ try:+ with default_storage.open(self.attribute.file_value.name, 'rb') as file_handle:+ processed_img = self._load_source_image_for_thumbnail(+ file_handle=file_handle,+ mime_type=mime_type,+ image_module=Image,+ image_ops_module=ImageOps,+ )++ if not processed_img:+ return False++ resampling = (+ Image.Resampling.LANCZOS+ if hasattr(Image, 'Resampling')+ else Image.LANCZOS+ )+ processed_img.thumbnail(self.THUMBNAIL_SIZE, resampling)++ if processed_img.mode not in ('RGB', 'RGBA'):+ if 'A' in processed_img.getbands():+ processed_img = processed_img.convert('RGBA')+ else:+ processed_img = processed_img.convert('RGB')++ bytes_buffer = BytesIO()+ processed_img.save(bytes_buffer, format='PNG', optimize=True)+ thumbnail_content = ContentFile(bytes_buffer.getvalue())++ if default_storage.exists(thumbnail_path):+ default_storage.delete(thumbnail_path)++ default_storage.save(thumbnail_path, thumbnail_content)+ return True+ except UnidentifiedImageError:+ logger.warning( f'Cannot generate thumbnail due to unrecognized image content: {self.attribute.file_value.name}' )+ except Exception as e:+ logger.warning( f'Error generating thumbnail for {self.attribute.file_value.name}: {e}' )+ return Falsediff --git a/src/hi/requirements/base.txt b/src/hi/requirements/base.txtindex 9ea25040..55b5e9b3 100644--- a/src/hi/requirements/base.txt+++ b/src/hi/requirements/base.txt@@ -13,6 +13,7 @@ gunicorn==23.0.0idna==3.10multidict==6.0.5numpy==2.1.0+pdf2image==1.17.0pillow==12.2.0Pint==0.25psutil==6.0.0diff --git a/src/hi/static/css/attribute.css b/src/hi/static/css/attribute.cssindex f042602a..58680db8 100644--- a/src/hi/static/css/attribute.css+++ b/src/hi/static/css/attribute.css@@ -163,6 +163,8 @@display: flex;flex-direction: column;align-items: center;+ justify-content: center;+ min-height: 120px;padding: 1rem;/* Diagonal hatch pattern background */background: repeating-linear-gradient(@@ -176,6 +178,25 @@cursor: pointer;}+.attr-v2-file-thumbnail.is-document {+ min-height: 140px;+}++.attr-v2-file-thumbnail.has-thumbnail {+ padding: 0;+ align-items: stretch;+ background: #1f2328;+ overflow: hidden;+ height: 180px;+}++.attr-v2-file-thumbnail-image {+ width: 100%;+ height: 100%;+ object-fit: contain;+ display: block;+}+.attr-v2-file-type-label {font-size: 0.8rem;font-weight: 700;