prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Resurrect script to process photos to the DB
  Now we are having script processing photos to the DB
  `shopelectro/management/commands/images.py`
  
  Since we have no tests for it, code may become stale. Resurrect it and move products to the prod
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `shopelectro/logic/header.py`
  Content:
  ```
  1 import typing
  2 from functools import lru_cache
  3 
  4 from django.conf import settings
  5 from django.db.models import Q
  6 
  7 from pages import models as pages_models
  8 from shopelectro import models
  9 
  10 
  11 class Menu:
  12     DICT_TYPE = typing.Dict[models.CategoryPage, typing.List[models.CategoryPage]]
  13 
  14     @staticmethod
  15     def roots() -> pages_models.PageQuerySet:
  16         """
  17         QuerySet with header menu items.
  18 
  19         Contains root categories.
  20         Result can be tuned HEADER_LINKS settings option.
  21         """
  22         return (
  23             pages_models.Page.objects.active()
  24             .filter(
  25                 Q(slug__in=settings.HEADER_LINKS['add'])
  26                 | (
  27                     # @todo #974:30m  Optimize the header menu query.
  28                     #  Fetch catalog page for the header menu at the same query.
  29                     #  root category pages.
  30                     Q(parent=pages_models.CustomPage.objects.filter(slug='catalog'))
  31                     & Q(type='model')
  32                     & Q(related_model_name=models.Category._meta.db_table)
  33                     & ~Q(slug__in=settings.HEADER_LINKS['exclude'])
  34                 )
  35             )
  36             .order_by('position')
  37         )
  38 
  39     @lru_cache(maxsize=1)
  40     def as_dict(self) -> DICT_TYPE:
  41         return {
  42             root: list(
  43                 root.get_children()
  44                 .filter(type='model')
  45                 .filter(related_model_name=models.Category._meta.db_table)
  46             )
  47             for root in self.roots().iterator()
  48         }
  49
  ```
  
  Path: `shopelectro/management/commands/images.py`
  Content:
  ```
  1 """Create Image objects from folder with image files."""
  2 import os
  3 
  4 from django.conf import settings
  5 from django.core.files.images import ImageFile
  6 from django.core.management.base import BaseCommand
  7 
  8 from images.models import Image
  9 from pages.models import Page
  10 from shopelectro.models import Product
  11 
  12 
  13 IMAGES_ROOT_FOLDER_NAME = os.path.join(settings.MEDIA_ROOT, 'products')
  14 
  15 
  16 def create_image_models():
  17 
  18     def iter_dirs(path: str):
  19         return (dir_ for dir_ in os.scandir(path) if dir_.is_dir())
  20 
  21     def iter_files(path: str):
  22         return (file_ for file_ in os.scandir(path) if file_.is_file())
  23 
  24     def get_page(product_id: int) -> Page:
  25         product_ = Product.objects.filter(id=product_id).first()
  26         return product_.page if product_ else None
  27 
  28     def create_image_model(file_, product_id: int, slug):
  29         file_short_name, _ = os.path.splitext(file_.name)
  30 
  31         # skip images, resized to small size
  32         if file_short_name == 'small':
  33             return
  34 
  35         # create Image model object based on current image
  36         page = get_page(product_id=product_id)
  37         if not page:
  38             return
  39         # don't use bulk create, because save() isn't hooked with it
  40         # http://bit.ly/django_bulk_create
  41         Image.objects.create(
  42             model=page,
  43             # autoincrement file names: '1.jpg', '2.jpg' and so on
  44             slug=slug,
  45             image=ImageFile(open(file_.path, mode='rb')),
  46             is_main=(file_short_name == 'main')
  47         )
  48 
  49     if not os.path.isdir(IMAGES_ROOT_FOLDER_NAME) or len(Image.objects.all()):
  50         return
  51 
  52     # run over every image in every folder
  53     for dir_ in iter_dirs(IMAGES_ROOT_FOLDER_NAME):
  54         for slug_index, file in enumerate(iter_files(dir_.path)):
  55             create_image_model(
  56                 file_=file,
  57                 product_id=int(dir_.name),
  58                 slug=str(slug_index)
  59             )
  60     # old folder stays in fs as backup of old photos
  61 
  62 
  63 class Command(BaseCommand):
  64 
  65     def handle(self, *args, **kwargs):
  66         create_image_models()
  67
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/shopelectro/logic/header.py b/shopelectro/logic/header.py
  --- a/shopelectro/logic/header.py
  +++ b/shopelectro/logic/header.py
  @@ -14,7 +14,7 @@
       @staticmethod
       def roots() -> pages_models.PageQuerySet:
           """
  -        QuerySet with header menu items.
  +        Queryset with header menu items.
   
           Contains root categories.
           Result can be tuned HEADER_LINKS settings option.
  diff --git a/shopelectro/management/commands/images.py b/shopelectro/management/commands/images.py
  --- a/shopelectro/management/commands/images.py
  +++ b/shopelectro/management/commands/images.py
  @@ -9,7 +9,6 @@
   from pages.models import Page
   from shopelectro.models import Product
   
  -
   IMAGES_ROOT_FOLDER_NAME = os.path.join(settings.MEDIA_ROOT, 'products')
   
   
  @@ -22,7 +21,7 @@
           return (file_ for file_ in os.scandir(path) if file_.is_file())
   
       def get_page(product_id: int) -> Page:
  -        product_ = Product.objects.filter(id=product_id).first()
  +        product_ = Product.objects.filter(vendor_code=product_id).first()
           return product_.page if product_ else None
   
       def create_image_model(file_, product_id: int, slug):
  @@ -42,6 +41,7 @@
               model=page,
               # autoincrement file names: '1.jpg', '2.jpg' and so on
               slug=slug,
  +            # copies file with to the new path on create
               image=ImageFile(open(file_.path, mode='rb')),
               is_main=(file_short_name == 'main')
           )
  
verification_info: {"golden_diff": "diff --git a/shopelectro/logic/header.py b/shopelectro/logic/header.py\n--- a/shopelectro/logic/header.py\n+++ b/shopelectro/logic/header.py\n@@ -14,7 +14,7 @@\n     @staticmethod\n     def roots() -> pages_models.PageQuerySet:\n         \"\"\"\n-        QuerySet with header menu items.\n+        Queryset with header menu items.\n \n         Contains root categories.\n         Result can be tuned HEADER_LINKS settings option.\ndiff --git a/shopelectro/management/commands/images.py b/shopelectro/management/commands/images.py\n--- a/shopelectro/management/commands/images.py\n+++ b/shopelectro/management/commands/images.py\n@@ -9,7 +9,6 @@\n from pages.models import Page\n from shopelectro.models import Product\n \n-\n IMAGES_ROOT_FOLDER_NAME = os.path.join(settings.MEDIA_ROOT, 'products')\n \n \n@@ -22,7 +21,7 @@\n         return (file_ for file_ in os.scandir(path) if file_.is_file())\n \n     def get_page(product_id: int) -> Page:\n-        product_ = Product.objects.filter(id=product_id).first()\n+        product_ = Product.objects.filter(vendor_code=product_id).first()\n         return product_.page if product_ else None\n \n     def create_image_model(file_, product_id: int, slug):\n@@ -42,6 +41,7 @@\n             model=page,\n             # autoincrement file names: '1.jpg', '2.jpg' and so on\n             slug=slug,\n+            # copies file with to the new path on create\n             image=ImageFile(open(file_.path, mode='rb')),\n             is_main=(file_short_name == 'main')\n         )\n", "issue": "Resurrect script to process photos to the DB\nNow we are having script processing photos to the DB\r\n`shopelectro/management/commands/images.py`\r\n\r\nSince we have no tests for it, code may become stale. Resurrect it and move products to the prod\n", "before_files": [{"content": "import typing\nfrom functools import lru_cache\n\nfrom django.conf import settings\nfrom django.db.models import Q\n\nfrom pages import models as pages_models\nfrom shopelectro import models\n\n\nclass Menu:\n    DICT_TYPE = typing.Dict[models.CategoryPage, typing.List[models.CategoryPage]]\n\n    @staticmethod\n    def roots() -> pages_models.PageQuerySet:\n        \"\"\"\n        QuerySet with header menu items.\n\n        Contains root categories.\n        Result can be tuned HEADER_LINKS settings option.\n        \"\"\"\n        return (\n            pages_models.Page.objects.active()\n            .filter(\n                Q(slug__in=settings.HEADER_LINKS['add'])\n                | (\n                    # @todo #974:30m  Optimize the header menu query.\n                    #  Fetch catalog page for the header menu at the same query.\n                    #  root category pages.\n                    Q(parent=pages_models.CustomPage.objects.filter(slug='catalog'))\n                    & Q(type='model')\n                    & Q(related_model_name=models.Category._meta.db_table)\n                    & ~Q(slug__in=settings.HEADER_LINKS['exclude'])\n                )\n            )\n            .order_by('position')\n        )\n\n    @lru_cache(maxsize=1)\n    def as_dict(self) -> DICT_TYPE:\n        return {\n            root: list(\n                root.get_children()\n                .filter(type='model')\n                .filter(related_model_name=models.Category._meta.db_table)\n            )\n            for root in self.roots().iterator()\n        }\n", "path": "shopelectro/logic/header.py"}, {"content": "\"\"\"Create Image objects from folder with image files.\"\"\"\nimport os\n\nfrom django.conf import settings\nfrom django.core.files.images import ImageFile\nfrom django.core.management.base import BaseCommand\n\nfrom images.models import Image\nfrom pages.models import Page\nfrom shopelectro.models import Product\n\n\nIMAGES_ROOT_FOLDER_NAME = os.path.join(settings.MEDIA_ROOT, 'products')\n\n\ndef create_image_models():\n\n    def iter_dirs(path: str):\n        return (dir_ for dir_ in os.scandir(path) if dir_.is_dir())\n\n    def iter_files(path: str):\n        return (file_ for file_ in os.scandir(path) if file_.is_file())\n\n    def get_page(product_id: int) -> Page:\n        product_ = Product.objects.filter(id=product_id).first()\n        return product_.page if product_ else None\n\n    def create_image_model(file_, product_id: int, slug):\n        file_short_name, _ = os.path.splitext(file_.name)\n\n        # skip images, resized to small size\n        if file_short_name == 'small':\n            return\n\n        # create Image model object based on current image\n        page = get_page(product_id=product_id)\n        if not page:\n            return\n        # don't use bulk create, because save() isn't hooked with it\n        # http://bit.ly/django_bulk_create\n        Image.objects.create(\n            model=page,\n            # autoincrement file names: '1.jpg', '2.jpg' and so on\n            slug=slug,\n            image=ImageFile(open(file_.path, mode='rb')),\n            is_main=(file_short_name == 'main')\n        )\n\n    if not os.path.isdir(IMAGES_ROOT_FOLDER_NAME) or len(Image.objects.all()):\n        return\n\n    # run over every image in every folder\n    for dir_ in iter_dirs(IMAGES_ROOT_FOLDER_NAME):\n        for slug_index, file in enumerate(iter_files(dir_.path)):\n            create_image_model(\n                file_=file,\n                product_id=int(dir_.name),\n                slug=str(slug_index)\n            )\n    # old folder stays in fs as backup of old photos\n\n\nclass Command(BaseCommand):\n\n    def handle(self, *args, **kwargs):\n        create_image_models()\n", "path": "shopelectro/management/commands/images.py"}], "after_files": [{"content": "import typing\nfrom functools import lru_cache\n\nfrom django.conf import settings\nfrom django.db.models import Q\n\nfrom pages import models as pages_models\nfrom shopelectro import models\n\n\nclass Menu:\n    DICT_TYPE = typing.Dict[models.CategoryPage, typing.List[models.CategoryPage]]\n\n    @staticmethod\n    def roots() -> pages_models.PageQuerySet:\n        \"\"\"\n        Queryset with header menu items.\n\n        Contains root categories.\n        Result can be tuned HEADER_LINKS settings option.\n        \"\"\"\n        return (\n            pages_models.Page.objects.active()\n            .filter(\n                Q(slug__in=settings.HEADER_LINKS['add'])\n                | (\n                    # @todo #974:30m  Optimize the header menu query.\n                    #  Fetch catalog page for the header menu at the same query.\n                    #  root category pages.\n                    Q(parent=pages_models.CustomPage.objects.filter(slug='catalog'))\n                    & Q(type='model')\n                    & Q(related_model_name=models.Category._meta.db_table)\n                    & ~Q(slug__in=settings.HEADER_LINKS['exclude'])\n                )\n            )\n            .order_by('position')\n        )\n\n    @lru_cache(maxsize=1)\n    def as_dict(self) -> DICT_TYPE:\n        return {\n            root: list(\n                root.get_children()\n                .filter(type='model')\n                .filter(related_model_name=models.Category._meta.db_table)\n            )\n            for root in self.roots().iterator()\n        }\n", "path": "shopelectro/logic/header.py"}, {"content": "\"\"\"Create Image objects from folder with image files.\"\"\"\nimport os\n\nfrom django.conf import settings\nfrom django.core.files.images import ImageFile\nfrom django.core.management.base import BaseCommand\n\nfrom images.models import Image\nfrom pages.models import Page\nfrom shopelectro.models import Product\n\nIMAGES_ROOT_FOLDER_NAME = os.path.join(settings.MEDIA_ROOT, 'products')\n\n\ndef create_image_models():\n\n    def iter_dirs(path: str):\n        return (dir_ for dir_ in os.scandir(path) if dir_.is_dir())\n\n    def iter_files(path: str):\n        return (file_ for file_ in os.scandir(path) if file_.is_file())\n\n    def get_page(product_id: int) -> Page:\n        product_ = Product.objects.filter(vendor_code=product_id).first()\n        return product_.page if product_ else None\n\n    def create_image_model(file_, product_id: int, slug):\n        file_short_name, _ = os.path.splitext(file_.name)\n\n        # skip images, resized to small size\n        if file_short_name == 'small':\n            return\n\n        # create Image model object based on current image\n        page = get_page(product_id=product_id)\n        if not page:\n            return\n        # don't use bulk create, because save() isn't hooked with it\n        # http://bit.ly/django_bulk_create\n        Image.objects.create(\n            model=page,\n            # autoincrement file names: '1.jpg', '2.jpg' and so on\n            slug=slug,\n            # copies file with to the new path on create\n            image=ImageFile(open(file_.path, mode='rb')),\n            is_main=(file_short_name == 'main')\n        )\n\n    if not os.path.isdir(IMAGES_ROOT_FOLDER_NAME) or len(Image.objects.all()):\n        return\n\n    # run over every image in every folder\n    for dir_ in iter_dirs(IMAGES_ROOT_FOLDER_NAME):\n        for slug_index, file in enumerate(iter_files(dir_.path)):\n            create_image_model(\n                file_=file,\n                product_id=int(dir_.name),\n                slug=str(slug_index)\n            )\n    # old folder stays in fs as backup of old photos\n\n\nclass Command(BaseCommand):\n\n    def handle(self, *args, **kwargs):\n        create_image_models()\n", "path": "shopelectro/management/commands/images.py"}]}