We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[Bug]: UnidentifiedImageError when using "Batch Process" in "Extras"
### Is there an existing issue for this?

- [X] I have searched the existing issues and checked the recent builds/commits

### What happened?

Hello,

I'm trying to upscale a bunch of images in the "Extras" Tab. When I pick an image in the "Single Image" tab it works perfectly fine. But when I pick the exact same imagefile in the "Batch Process" and hit "Generate" I instantly get this error message in the UI:

UnidentifiedImageError: cannot identify image file <tempfile._TemporaryFileWrapper object at 0x000001F589DBF1F0>
Time taken: 0.00sTorch active/reserved: 1/2 MiB, Sys VRAM: 1277/4096 MiB (31.18%)

In the CMD it looks like this:
Error completing request
Arguments: (1, <PIL.Image.Image image mode=RGB size=960x1200 at 0x1F589DBF160>, [<tempfile._TemporaryFileWrapper object at 0x000001F589DBF1F0>], '', '', True, 0, 4, 512, 512, True, 'SwinIR_4x', 'None', 0, 0, 0, 0) {}
Traceback (most recent call last):
  File "C:\AI\stable-diffusion-webui\modules\call_queue.py", line 56, in f
    res = list(func(*args, **kwargs))
  File "C:\AI\stable-diffusion-webui\modules\call_queue.py", line 37, in f
    res = func(*args, **kwargs)
  File "C:\AI\stable-diffusion-webui\modules\postprocessing.py", line 21, in run_postprocessing
    image = Image.open(img)
  File "C:\AI\stable-diffusion-webui\venv\lib\site-packages\PIL\Image.py", line 3283, in open
    raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file <tempfile._TemporaryFileWrapper object at 0x000001F589DBF1F0>




### Steps to reproduce the problem

1. Go to .... Extras, Batch Process
2. Press .... Import to add the image, and press Generate


### What should have happened?

It should create the upscaled image, just like in the Single Image tab.

### Commit where the problem happens

a0d07fb5

### What platforms do you use to access the UI ?

Windows

### What browsers do you use to access the UI ?

Google Chrome

### Command Line Arguments

```Shell
git pull
pause 

 --xformers --medvram
```


### List of extensions

no

### Console logs

```Shell
C:\AI\stable-diffusion-webui>git pull
Already up to date.

C:\AI\stable-diffusion-webui>pause
Drücken Sie eine beliebige Taste . . .
venv "C:\AI\stable-diffusion-webui\venv\Scripts\Python.exe"
Python 3.10.10 (tags/v3.10.10:aad5f6a, Feb  7 2023, 17:20:36) [MSC v.1929 64 bit (AMD64)]
Commit hash: a0d07fb5807ad55c8ccfdfc9a6d9ae3c62b9d211
Installing requirements for Web UI
Launching Web UI with arguments: --xformers --medvram
Loading weights [cc6cb27103] from C:\AI\stable-diffusion-webui\models\Stable-diffusion\model.ckpt
Creating model from config: C:\AI\stable-diffusion-webui\configs\v1-inference.yaml
LatentDiffusion: Running in eps-prediction mode
DiffusionWrapper has 859.52 M params.
Applying cross attention optimization (Doggettx).
Textual inversion embeddings loaded(0):
Model loaded in 3.2s (load weights from disk: 1.6s, create model: 0.5s, apply weights to model: 0.5s, apply half(): 0.6s).
Running on local URL:  http://127.0.0.1:7860

To create a public link, set `share=True` in `launch()`.
Startup time: 12.3s (import torch: 2.7s, import gradio: 1.5s, import ldm: 0.4s, other imports: 1.3s, setup codeformer: 0.1s, load scripts: 2.2s, load SD checkpoint: 3.5s, create ui: 0.3s, gradio launch: 0.1s).
Error completing request
Arguments: (1, None, [<tempfile._TemporaryFileWrapper object at 0x000001E5841F11E0>], '', '', True, 0, 4, 512, 512, True, 'None', 'None', 0, 0, 0, 0) {}
Traceback (most recent call last):
  File "C:\AI\stable-diffusion-webui\modules\call_queue.py", line 56, in f
    res = list(func(*args, **kwargs))
  File "C:\AI\stable-diffusion-webui\modules\call_queue.py", line 37, in f
    res = func(*args, **kwargs)
  File "C:\AI\stable-diffusion-webui\modules\postprocessing.py", line 21, in run_postprocessing
    image = Image.open(img)
  File "C:\AI\stable-diffusion-webui\venv\lib\site-packages\PIL\Image.py", line 3283, in open
    raise UnidentifiedImageError(msg)
PIL.UnidentifiedImageError: cannot identify image file <tempfile._TemporaryFileWrapper object at 0x000001E5841F11E0>
```


### Additional information

_No response_

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `modules/ui_postprocessing.py`
Content:
```
1 import gradio as gr
2 from modules import scripts_postprocessing, scripts, shared, gfpgan_model, codeformer_model, ui_common, postprocessing, call_queue
3 import modules.generation_parameters_copypaste as parameters_copypaste
4 
5 
6 def create_ui():
7     tab_index = gr.State(value=0)
8 
9     with gr.Row().style(equal_height=False, variant='compact'):
10         with gr.Column(variant='compact'):
11             with gr.Tabs(elem_id="mode_extras"):
12                 with gr.TabItem('Single Image', elem_id="extras_single_tab") as tab_single:
13                     extras_image = gr.Image(label="Source", source="upload", interactive=True, type="pil", elem_id="extras_image")
14 
15                 with gr.TabItem('Batch Process', elem_id="extras_batch_process_tab") as tab_batch:
16                     image_batch = gr.File(label="Batch Process", file_count="multiple", interactive=True, type="file", elem_id="extras_image_batch")
17 
18                 with gr.TabItem('Batch from Directory', elem_id="extras_batch_directory_tab") as tab_batch_dir:
19                     extras_batch_input_dir = gr.Textbox(label="Input directory", **shared.hide_dirs, placeholder="A directory on the same machine where the server is running.", elem_id="extras_batch_input_dir")
20                     extras_batch_output_dir = gr.Textbox(label="Output directory", **shared.hide_dirs, placeholder="Leave blank to save images to the default path.", elem_id="extras_batch_output_dir")
21                     show_extras_results = gr.Checkbox(label='Show result images', value=True, elem_id="extras_show_extras_results")
22 
23             submit = gr.Button('Generate', elem_id="extras_generate", variant='primary')
24 
25             script_inputs = scripts.scripts_postproc.setup_ui()
26 
27         with gr.Column():
28             result_images, html_info_x, html_info, html_log = ui_common.create_output_panel("extras", shared.opts.outdir_extras_samples)
29 
30     tab_single.select(fn=lambda: 0, inputs=[], outputs=[tab_index])
31     tab_batch.select(fn=lambda: 1, inputs=[], outputs=[tab_index])
32     tab_batch_dir.select(fn=lambda: 2, inputs=[], outputs=[tab_index])
33 
34     submit.click(
35         fn=call_queue.wrap_gradio_gpu_call(postprocessing.run_postprocessing, extra_outputs=[None, '']),
36         inputs=[
37             tab_index,
38             extras_image,
39             image_batch,
40             extras_batch_input_dir,
41             extras_batch_output_dir,
42             show_extras_results,
43             *script_inputs
44         ],
45         outputs=[
46             result_images,
47             html_info_x,
48             html_info,
49         ]
50     )
51 
52     parameters_copypaste.add_paste_fields("extras", extras_image, None)
53 
54     extras_image.change(
55         fn=scripts.scripts_postproc.image_changed,
56         inputs=[], outputs=[]
57     )
58
```

Path: `modules/postprocessing.py`
Content:
```
1 import os
2 
3 from PIL import Image
4 
5 from modules import shared, images, devices, scripts, scripts_postprocessing, ui_common, generation_parameters_copypaste
6 from modules.shared import opts
7 
8 
9 def run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output: bool = True):
10     devices.torch_gc()
11 
12     shared.state.begin()
13     shared.state.job = 'extras'
14 
15     image_data = []
16     image_names = []
17     outputs = []
18 
19     if extras_mode == 1:
20         for img in image_folder:
21             if isinstance(img, Image.Image):
22                 image = img
23                 fn = ''
24             else:
25                 image = Image.open(img)
26                 fn = os.path.splitext(img.orig_name)[0]
27 
28             image_data.append(image)
29             image_names.append(fn)
30     elif extras_mode == 2:
31         assert not shared.cmd_opts.hide_ui_dir_config, '--hide-ui-dir-config option must be disabled'
32         assert input_dir, 'input directory not selected'
33 
34         image_list = shared.listfiles(input_dir)
35         for filename in image_list:
36             try:
37                 image = Image.open(filename)
38             except Exception:
39                 continue
40             image_data.append(image)
41             image_names.append(filename)
42     else:
43         assert image, 'image not selected'
44 
45         image_data.append(image)
46         image_names.append(None)
47 
48     if extras_mode == 2 and output_dir != '':
49         outpath = output_dir
50     else:
51         outpath = opts.outdir_samples or opts.outdir_extras_samples
52 
53     infotext = ''
54 
55     for image, name in zip(image_data, image_names):
56         shared.state.textinfo = name
57 
58         existing_pnginfo = image.info or {}
59 
60         pp = scripts_postprocessing.PostprocessedImage(image.convert("RGB"))
61 
62         scripts.scripts_postproc.run(pp, args)
63 
64         if opts.use_original_name_batch and name is not None:
65             basename = os.path.splitext(os.path.basename(name))[0]
66         else:
67             basename = ''
68 
69         infotext = ", ".join([k if k == v else f'{k}: {generation_parameters_copypaste.quote(v)}' for k, v in pp.info.items() if v is not None])
70 
71         if opts.enable_pnginfo:
72             pp.image.info = existing_pnginfo
73             pp.image.info["postprocessing"] = infotext
74 
75         if save_output:
76             images.save_image(pp.image, path=outpath, basename=basename, seed=None, prompt=None, extension=opts.samples_format, info=infotext, short_filename=True, no_prompt=True, grid=False, pnginfo_section_name="extras", existing_info=existing_pnginfo, forced_filename=None)
77 
78         if extras_mode != 2 or show_extras_results:
79             outputs.append(pp.image)
80 
81     devices.torch_gc()
82 
83     return outputs, ui_common.plaintext_to_html(infotext), ''
84 
85 
86 def run_extras(extras_mode, resize_mode, image, image_folder, input_dir, output_dir, show_extras_results, gfpgan_visibility, codeformer_visibility, codeformer_weight, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, upscale_first: bool, save_output: bool = True):
87     """old handler for API"""
88 
89     args = scripts.scripts_postproc.create_args_for_run({
90         "Upscale": {
91             "upscale_mode": resize_mode,
92             "upscale_by": upscaling_resize,
93             "upscale_to_width": upscaling_resize_w,
94             "upscale_to_height": upscaling_resize_h,
95             "upscale_crop": upscaling_crop,
96             "upscaler_1_name": extras_upscaler_1,
97             "upscaler_2_name": extras_upscaler_2,
98             "upscaler_2_visibility": extras_upscaler_2_visibility,
99         },
100         "GFPGAN": {
101             "gfpgan_visibility": gfpgan_visibility,
102         },
103         "CodeFormer": {
104             "codeformer_visibility": codeformer_visibility,
105             "codeformer_weight": codeformer_weight,
106         },
107     })
108 
109     return run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output=save_output)
110
```
--- 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()

```

diff --git a/modules/postprocessing.py b/modules/postprocessing.py
--- a/modules/postprocessing.py
+++ b/modules/postprocessing.py
@@ -1,4 +1,6 @@
 import os
+import tempfile
+from typing import List
 
 from PIL import Image
 
@@ -6,7 +8,7 @@
 from modules.shared import opts
 
 
-def run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output: bool = True):
+def run_postprocessing(extras_mode, image, image_folder: List[tempfile.NamedTemporaryFile], input_dir, output_dir, show_extras_results, *args, save_output: bool = True):
     devices.torch_gc()
 
     shared.state.begin()
@@ -22,7 +24,7 @@
                 image = img
                 fn = ''
             else:
-                image = Image.open(img)
+                image = Image.open(os.path.abspath(img.name))
                 fn = os.path.splitext(img.orig_name)[0]
 
             image_data.append(image)
diff --git a/modules/ui_postprocessing.py b/modules/ui_postprocessing.py
--- a/modules/ui_postprocessing.py
+++ b/modules/ui_postprocessing.py
@@ -13,7 +13,7 @@
                     extras_image = gr.Image(label="Source", source="upload", interactive=True, type="pil", elem_id="extras_image")
 
                 with gr.TabItem('Batch Process', elem_id="extras_batch_process_tab") as tab_batch:
-                    image_batch = gr.File(label="Batch Process", file_count="multiple", interactive=True, type="file", elem_id="extras_image_batch")
+                    image_batch = gr.Files(label="Batch Process", interactive=True, elem_id="extras_image_batch")
 
                 with gr.TabItem('Batch from Directory', elem_id="extras_batch_directory_tab") as tab_batch_dir:
                     extras_batch_input_dir = gr.Textbox(label="Input directory", **shared.hide_dirs, placeholder="A directory on the same machine where the server is running.", elem_id="extras_batch_input_dir")

{"golden_diff": "diff --git a/modules/postprocessing.py b/modules/postprocessing.py\n--- a/modules/postprocessing.py\n+++ b/modules/postprocessing.py\n@@ -1,4 +1,6 @@\n import os\r\n+import tempfile\r\n+from typing import List\r\n \r\n from PIL import Image\r\n \r\n@@ -6,7 +8,7 @@\n from modules.shared import opts\r\n \r\n \r\n-def run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output: bool = True):\r\n+def run_postprocessing(extras_mode, image, image_folder: List[tempfile.NamedTemporaryFile], input_dir, output_dir, show_extras_results, *args, save_output: bool = True):\r\n     devices.torch_gc()\r\n \r\n     shared.state.begin()\r\n@@ -22,7 +24,7 @@\n                 image = img\r\n                 fn = ''\r\n             else:\r\n-                image = Image.open(img)\r\n+                image = Image.open(os.path.abspath(img.name))\r\n                 fn = os.path.splitext(img.orig_name)[0]\r\n \r\n             image_data.append(image)\r\ndiff --git a/modules/ui_postprocessing.py b/modules/ui_postprocessing.py\n--- a/modules/ui_postprocessing.py\n+++ b/modules/ui_postprocessing.py\n@@ -13,7 +13,7 @@\n                     extras_image = gr.Image(label=\"Source\", source=\"upload\", interactive=True, type=\"pil\", elem_id=\"extras_image\")\r\n \r\n                 with gr.TabItem('Batch Process', elem_id=\"extras_batch_process_tab\") as tab_batch:\r\n-                    image_batch = gr.File(label=\"Batch Process\", file_count=\"multiple\", interactive=True, type=\"file\", elem_id=\"extras_image_batch\")\r\n+                    image_batch = gr.Files(label=\"Batch Process\", interactive=True, elem_id=\"extras_image_batch\")\r\n \r\n                 with gr.TabItem('Batch from Directory', elem_id=\"extras_batch_directory_tab\") as tab_batch_dir:\r\n                     extras_batch_input_dir = gr.Textbox(label=\"Input directory\", **shared.hide_dirs, placeholder=\"A directory on the same machine where the server is running.\", elem_id=\"extras_batch_input_dir\")\n", "issue": "[Bug]: UnidentifiedImageError when using \"Batch Process\" in \"Extras\"\n### Is there an existing issue for this?\n\n- [X] I have searched the existing issues and checked the recent builds/commits\n\n### What happened?\n\nHello,\r\n\r\nI'm trying to upscale a bunch of images in the \"Extras\" Tab. When I pick an image in the \"Single Image\" tab it works perfectly fine. But when I pick the exact same imagefile in the \"Batch Process\" and hit \"Generate\" I instantly get this error message in the UI:\r\n\r\nUnidentifiedImageError: cannot identify image file <tempfile._TemporaryFileWrapper object at 0x000001F589DBF1F0>\r\nTime taken: 0.00sTorch active/reserved: 1/2 MiB, Sys VRAM: 1277/4096 MiB (31.18%)\r\n\r\nIn the CMD it looks like this:\r\nError completing request\r\nArguments: (1, <PIL.Image.Image image mode=RGB size=960x1200 at 0x1F589DBF160>, [<tempfile._TemporaryFileWrapper object at 0x000001F589DBF1F0>], '', '', True, 0, 4, 512, 512, True, 'SwinIR_4x', 'None', 0, 0, 0, 0) {}\r\nTraceback (most recent call last):\r\n  File \"C:\\AI\\stable-diffusion-webui\\modules\\call_queue.py\", line 56, in f\r\n    res = list(func(*args, **kwargs))\r\n  File \"C:\\AI\\stable-diffusion-webui\\modules\\call_queue.py\", line 37, in f\r\n    res = func(*args, **kwargs)\r\n  File \"C:\\AI\\stable-diffusion-webui\\modules\\postprocessing.py\", line 21, in run_postprocessing\r\n    image = Image.open(img)\r\n  File \"C:\\AI\\stable-diffusion-webui\\venv\\lib\\site-packages\\PIL\\Image.py\", line 3283, in open\r\n    raise UnidentifiedImageError(msg)\r\nPIL.UnidentifiedImageError: cannot identify image file <tempfile._TemporaryFileWrapper object at 0x000001F589DBF1F0>\r\n\r\n\r\n\n\n### Steps to reproduce the problem\n\n1. Go to .... Extras, Batch Process\r\n2. Press .... Import to add the image, and press Generate\r\n\n\n### What should have happened?\n\nIt should create the upscaled image, just like in the Single Image tab.\n\n### Commit where the problem happens\n\na0d07fb5\n\n### What platforms do you use to access the UI ?\n\nWindows\n\n### What browsers do you use to access the UI ?\n\nGoogle Chrome\n\n### Command Line Arguments\n\n```Shell\ngit pull\r\npause \r\n\r\n --xformers --medvram\n```\n\n\n### List of extensions\n\nno\n\n### Console logs\n\n```Shell\nC:\\AI\\stable-diffusion-webui>git pull\r\nAlready up to date.\r\n\r\nC:\\AI\\stable-diffusion-webui>pause\r\nDr\u00fccken Sie eine beliebige Taste . . .\r\nvenv \"C:\\AI\\stable-diffusion-webui\\venv\\Scripts\\Python.exe\"\r\nPython 3.10.10 (tags/v3.10.10:aad5f6a, Feb  7 2023, 17:20:36) [MSC v.1929 64 bit (AMD64)]\r\nCommit hash: a0d07fb5807ad55c8ccfdfc9a6d9ae3c62b9d211\r\nInstalling requirements for Web UI\r\nLaunching Web UI with arguments: --xformers --medvram\r\nLoading weights [cc6cb27103] from C:\\AI\\stable-diffusion-webui\\models\\Stable-diffusion\\model.ckpt\r\nCreating model from config: C:\\AI\\stable-diffusion-webui\\configs\\v1-inference.yaml\r\nLatentDiffusion: Running in eps-prediction mode\r\nDiffusionWrapper has 859.52 M params.\r\nApplying cross attention optimization (Doggettx).\r\nTextual inversion embeddings loaded(0):\r\nModel loaded in 3.2s (load weights from disk: 1.6s, create model: 0.5s, apply weights to model: 0.5s, apply half(): 0.6s).\r\nRunning on local URL:  http://127.0.0.1:7860\r\n\r\nTo create a public link, set `share=True` in `launch()`.\r\nStartup time: 12.3s (import torch: 2.7s, import gradio: 1.5s, import ldm: 0.4s, other imports: 1.3s, setup codeformer: 0.1s, load scripts: 2.2s, load SD checkpoint: 3.5s, create ui: 0.3s, gradio launch: 0.1s).\r\nError completing request\r\nArguments: (1, None, [<tempfile._TemporaryFileWrapper object at 0x000001E5841F11E0>], '', '', True, 0, 4, 512, 512, True, 'None', 'None', 0, 0, 0, 0) {}\r\nTraceback (most recent call last):\r\n  File \"C:\\AI\\stable-diffusion-webui\\modules\\call_queue.py\", line 56, in f\r\n    res = list(func(*args, **kwargs))\r\n  File \"C:\\AI\\stable-diffusion-webui\\modules\\call_queue.py\", line 37, in f\r\n    res = func(*args, **kwargs)\r\n  File \"C:\\AI\\stable-diffusion-webui\\modules\\postprocessing.py\", line 21, in run_postprocessing\r\n    image = Image.open(img)\r\n  File \"C:\\AI\\stable-diffusion-webui\\venv\\lib\\site-packages\\PIL\\Image.py\", line 3283, in open\r\n    raise UnidentifiedImageError(msg)\r\nPIL.UnidentifiedImageError: cannot identify image file <tempfile._TemporaryFileWrapper object at 0x000001E5841F11E0>\n```\n\n\n### Additional information\n\n_No response_\n", "before_files": [{"content": "import gradio as gr\r\nfrom modules import scripts_postprocessing, scripts, shared, gfpgan_model, codeformer_model, ui_common, postprocessing, call_queue\r\nimport modules.generation_parameters_copypaste as parameters_copypaste\r\n\r\n\r\ndef create_ui():\r\n    tab_index = gr.State(value=0)\r\n\r\n    with gr.Row().style(equal_height=False, variant='compact'):\r\n        with gr.Column(variant='compact'):\r\n            with gr.Tabs(elem_id=\"mode_extras\"):\r\n                with gr.TabItem('Single Image', elem_id=\"extras_single_tab\") as tab_single:\r\n                    extras_image = gr.Image(label=\"Source\", source=\"upload\", interactive=True, type=\"pil\", elem_id=\"extras_image\")\r\n\r\n                with gr.TabItem('Batch Process', elem_id=\"extras_batch_process_tab\") as tab_batch:\r\n                    image_batch = gr.File(label=\"Batch Process\", file_count=\"multiple\", interactive=True, type=\"file\", elem_id=\"extras_image_batch\")\r\n\r\n                with gr.TabItem('Batch from Directory', elem_id=\"extras_batch_directory_tab\") as tab_batch_dir:\r\n                    extras_batch_input_dir = gr.Textbox(label=\"Input directory\", **shared.hide_dirs, placeholder=\"A directory on the same machine where the server is running.\", elem_id=\"extras_batch_input_dir\")\r\n                    extras_batch_output_dir = gr.Textbox(label=\"Output directory\", **shared.hide_dirs, placeholder=\"Leave blank to save images to the default path.\", elem_id=\"extras_batch_output_dir\")\r\n                    show_extras_results = gr.Checkbox(label='Show result images', value=True, elem_id=\"extras_show_extras_results\")\r\n\r\n            submit = gr.Button('Generate', elem_id=\"extras_generate\", variant='primary')\r\n\r\n            script_inputs = scripts.scripts_postproc.setup_ui()\r\n\r\n        with gr.Column():\r\n            result_images, html_info_x, html_info, html_log = ui_common.create_output_panel(\"extras\", shared.opts.outdir_extras_samples)\r\n\r\n    tab_single.select(fn=lambda: 0, inputs=[], outputs=[tab_index])\r\n    tab_batch.select(fn=lambda: 1, inputs=[], outputs=[tab_index])\r\n    tab_batch_dir.select(fn=lambda: 2, inputs=[], outputs=[tab_index])\r\n\r\n    submit.click(\r\n        fn=call_queue.wrap_gradio_gpu_call(postprocessing.run_postprocessing, extra_outputs=[None, '']),\r\n        inputs=[\r\n            tab_index,\r\n            extras_image,\r\n            image_batch,\r\n            extras_batch_input_dir,\r\n            extras_batch_output_dir,\r\n            show_extras_results,\r\n            *script_inputs\r\n        ],\r\n        outputs=[\r\n            result_images,\r\n            html_info_x,\r\n            html_info,\r\n        ]\r\n    )\r\n\r\n    parameters_copypaste.add_paste_fields(\"extras\", extras_image, None)\r\n\r\n    extras_image.change(\r\n        fn=scripts.scripts_postproc.image_changed,\r\n        inputs=[], outputs=[]\r\n    )\r\n", "path": "modules/ui_postprocessing.py"}, {"content": "import os\r\n\r\nfrom PIL import Image\r\n\r\nfrom modules import shared, images, devices, scripts, scripts_postprocessing, ui_common, generation_parameters_copypaste\r\nfrom modules.shared import opts\r\n\r\n\r\ndef run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output: bool = True):\r\n    devices.torch_gc()\r\n\r\n    shared.state.begin()\r\n    shared.state.job = 'extras'\r\n\r\n    image_data = []\r\n    image_names = []\r\n    outputs = []\r\n\r\n    if extras_mode == 1:\r\n        for img in image_folder:\r\n            if isinstance(img, Image.Image):\r\n                image = img\r\n                fn = ''\r\n            else:\r\n                image = Image.open(img)\r\n                fn = os.path.splitext(img.orig_name)[0]\r\n\r\n            image_data.append(image)\r\n            image_names.append(fn)\r\n    elif extras_mode == 2:\r\n        assert not shared.cmd_opts.hide_ui_dir_config, '--hide-ui-dir-config option must be disabled'\r\n        assert input_dir, 'input directory not selected'\r\n\r\n        image_list = shared.listfiles(input_dir)\r\n        for filename in image_list:\r\n            try:\r\n                image = Image.open(filename)\r\n            except Exception:\r\n                continue\r\n            image_data.append(image)\r\n            image_names.append(filename)\r\n    else:\r\n        assert image, 'image not selected'\r\n\r\n        image_data.append(image)\r\n        image_names.append(None)\r\n\r\n    if extras_mode == 2 and output_dir != '':\r\n        outpath = output_dir\r\n    else:\r\n        outpath = opts.outdir_samples or opts.outdir_extras_samples\r\n\r\n    infotext = ''\r\n\r\n    for image, name in zip(image_data, image_names):\r\n        shared.state.textinfo = name\r\n\r\n        existing_pnginfo = image.info or {}\r\n\r\n        pp = scripts_postprocessing.PostprocessedImage(image.convert(\"RGB\"))\r\n\r\n        scripts.scripts_postproc.run(pp, args)\r\n\r\n        if opts.use_original_name_batch and name is not None:\r\n            basename = os.path.splitext(os.path.basename(name))[0]\r\n        else:\r\n            basename = ''\r\n\r\n        infotext = \", \".join([k if k == v else f'{k}: {generation_parameters_copypaste.quote(v)}' for k, v in pp.info.items() if v is not None])\r\n\r\n        if opts.enable_pnginfo:\r\n            pp.image.info = existing_pnginfo\r\n            pp.image.info[\"postprocessing\"] = infotext\r\n\r\n        if save_output:\r\n            images.save_image(pp.image, path=outpath, basename=basename, seed=None, prompt=None, extension=opts.samples_format, info=infotext, short_filename=True, no_prompt=True, grid=False, pnginfo_section_name=\"extras\", existing_info=existing_pnginfo, forced_filename=None)\r\n\r\n        if extras_mode != 2 or show_extras_results:\r\n            outputs.append(pp.image)\r\n\r\n    devices.torch_gc()\r\n\r\n    return outputs, ui_common.plaintext_to_html(infotext), ''\r\n\r\n\r\ndef run_extras(extras_mode, resize_mode, image, image_folder, input_dir, output_dir, show_extras_results, gfpgan_visibility, codeformer_visibility, codeformer_weight, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, upscale_first: bool, save_output: bool = True):\r\n    \"\"\"old handler for API\"\"\"\r\n\r\n    args = scripts.scripts_postproc.create_args_for_run({\r\n        \"Upscale\": {\r\n            \"upscale_mode\": resize_mode,\r\n            \"upscale_by\": upscaling_resize,\r\n            \"upscale_to_width\": upscaling_resize_w,\r\n            \"upscale_to_height\": upscaling_resize_h,\r\n            \"upscale_crop\": upscaling_crop,\r\n            \"upscaler_1_name\": extras_upscaler_1,\r\n            \"upscaler_2_name\": extras_upscaler_2,\r\n            \"upscaler_2_visibility\": extras_upscaler_2_visibility,\r\n        },\r\n        \"GFPGAN\": {\r\n            \"gfpgan_visibility\": gfpgan_visibility,\r\n        },\r\n        \"CodeFormer\": {\r\n            \"codeformer_visibility\": codeformer_visibility,\r\n            \"codeformer_weight\": codeformer_weight,\r\n        },\r\n    })\r\n\r\n    return run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output=save_output)\r\n", "path": "modules/postprocessing.py"}], "after_files": [{"content": "import gradio as gr\r\nfrom modules import scripts_postprocessing, scripts, shared, gfpgan_model, codeformer_model, ui_common, postprocessing, call_queue\r\nimport modules.generation_parameters_copypaste as parameters_copypaste\r\n\r\n\r\ndef create_ui():\r\n    tab_index = gr.State(value=0)\r\n\r\n    with gr.Row().style(equal_height=False, variant='compact'):\r\n        with gr.Column(variant='compact'):\r\n            with gr.Tabs(elem_id=\"mode_extras\"):\r\n                with gr.TabItem('Single Image', elem_id=\"extras_single_tab\") as tab_single:\r\n                    extras_image = gr.Image(label=\"Source\", source=\"upload\", interactive=True, type=\"pil\", elem_id=\"extras_image\")\r\n\r\n                with gr.TabItem('Batch Process', elem_id=\"extras_batch_process_tab\") as tab_batch:\r\n                    image_batch = gr.Files(label=\"Batch Process\", interactive=True, elem_id=\"extras_image_batch\")\r\n\r\n                with gr.TabItem('Batch from Directory', elem_id=\"extras_batch_directory_tab\") as tab_batch_dir:\r\n                    extras_batch_input_dir = gr.Textbox(label=\"Input directory\", **shared.hide_dirs, placeholder=\"A directory on the same machine where the server is running.\", elem_id=\"extras_batch_input_dir\")\r\n                    extras_batch_output_dir = gr.Textbox(label=\"Output directory\", **shared.hide_dirs, placeholder=\"Leave blank to save images to the default path.\", elem_id=\"extras_batch_output_dir\")\r\n                    show_extras_results = gr.Checkbox(label='Show result images', value=True, elem_id=\"extras_show_extras_results\")\r\n\r\n            submit = gr.Button('Generate', elem_id=\"extras_generate\", variant='primary')\r\n\r\n            script_inputs = scripts.scripts_postproc.setup_ui()\r\n\r\n        with gr.Column():\r\n            result_images, html_info_x, html_info, html_log = ui_common.create_output_panel(\"extras\", shared.opts.outdir_extras_samples)\r\n\r\n    tab_single.select(fn=lambda: 0, inputs=[], outputs=[tab_index])\r\n    tab_batch.select(fn=lambda: 1, inputs=[], outputs=[tab_index])\r\n    tab_batch_dir.select(fn=lambda: 2, inputs=[], outputs=[tab_index])\r\n\r\n    submit.click(\r\n        fn=call_queue.wrap_gradio_gpu_call(postprocessing.run_postprocessing, extra_outputs=[None, '']),\r\n        inputs=[\r\n            tab_index,\r\n            extras_image,\r\n            image_batch,\r\n            extras_batch_input_dir,\r\n            extras_batch_output_dir,\r\n            show_extras_results,\r\n            *script_inputs\r\n        ],\r\n        outputs=[\r\n            result_images,\r\n            html_info_x,\r\n            html_info,\r\n        ]\r\n    )\r\n\r\n    parameters_copypaste.add_paste_fields(\"extras\", extras_image, None)\r\n\r\n    extras_image.change(\r\n        fn=scripts.scripts_postproc.image_changed,\r\n        inputs=[], outputs=[]\r\n    )\r\n", "path": "modules/ui_postprocessing.py"}, {"content": "import os\r\nimport tempfile\r\nfrom typing import List\r\n\r\nfrom PIL import Image\r\n\r\nfrom modules import shared, images, devices, scripts, scripts_postprocessing, ui_common, generation_parameters_copypaste\r\nfrom modules.shared import opts\r\n\r\n\r\ndef run_postprocessing(extras_mode, image, image_folder: List[tempfile.NamedTemporaryFile], input_dir, output_dir, show_extras_results, *args, save_output: bool = True):\r\n    devices.torch_gc()\r\n\r\n    shared.state.begin()\r\n    shared.state.job = 'extras'\r\n\r\n    image_data = []\r\n    image_names = []\r\n    outputs = []\r\n\r\n    if extras_mode == 1:\r\n        for img in image_folder:\r\n            if isinstance(img, Image.Image):\r\n                image = img\r\n                fn = ''\r\n            else:\r\n                image = Image.open(os.path.abspath(img.name))\r\n                fn = os.path.splitext(img.orig_name)[0]\r\n\r\n            image_data.append(image)\r\n            image_names.append(fn)\r\n    elif extras_mode == 2:\r\n        assert not shared.cmd_opts.hide_ui_dir_config, '--hide-ui-dir-config option must be disabled'\r\n        assert input_dir, 'input directory not selected'\r\n\r\n        image_list = shared.listfiles(input_dir)\r\n        for filename in image_list:\r\n            try:\r\n                image = Image.open(filename)\r\n            except Exception:\r\n                continue\r\n            image_data.append(image)\r\n            image_names.append(filename)\r\n    else:\r\n        assert image, 'image not selected'\r\n\r\n        image_data.append(image)\r\n        image_names.append(None)\r\n\r\n    if extras_mode == 2 and output_dir != '':\r\n        outpath = output_dir\r\n    else:\r\n        outpath = opts.outdir_samples or opts.outdir_extras_samples\r\n\r\n    infotext = ''\r\n\r\n    for image, name in zip(image_data, image_names):\r\n        shared.state.textinfo = name\r\n\r\n        existing_pnginfo = image.info or {}\r\n\r\n        pp = scripts_postprocessing.PostprocessedImage(image.convert(\"RGB\"))\r\n\r\n        scripts.scripts_postproc.run(pp, args)\r\n\r\n        if opts.use_original_name_batch and name is not None:\r\n            basename = os.path.splitext(os.path.basename(name))[0]\r\n        else:\r\n            basename = ''\r\n\r\n        infotext = \", \".join([k if k == v else f'{k}: {generation_parameters_copypaste.quote(v)}' for k, v in pp.info.items() if v is not None])\r\n\r\n        if opts.enable_pnginfo:\r\n            pp.image.info = existing_pnginfo\r\n            pp.image.info[\"postprocessing\"] = infotext\r\n\r\n        if save_output:\r\n            images.save_image(pp.image, path=outpath, basename=basename, seed=None, prompt=None, extension=opts.samples_format, info=infotext, short_filename=True, no_prompt=True, grid=False, pnginfo_section_name=\"extras\", existing_info=existing_pnginfo, forced_filename=None)\r\n\r\n        if extras_mode != 2 or show_extras_results:\r\n            outputs.append(pp.image)\r\n\r\n    devices.torch_gc()\r\n\r\n    return outputs, ui_common.plaintext_to_html(infotext), ''\r\n\r\n\r\ndef run_extras(extras_mode, resize_mode, image, image_folder, input_dir, output_dir, show_extras_results, gfpgan_visibility, codeformer_visibility, codeformer_weight, upscaling_resize, upscaling_resize_w, upscaling_resize_h, upscaling_crop, extras_upscaler_1, extras_upscaler_2, extras_upscaler_2_visibility, upscale_first: bool, save_output: bool = True):\r\n    \"\"\"old handler for API\"\"\"\r\n\r\n    args = scripts.scripts_postproc.create_args_for_run({\r\n        \"Upscale\": {\r\n            \"upscale_mode\": resize_mode,\r\n            \"upscale_by\": upscaling_resize,\r\n            \"upscale_to_width\": upscaling_resize_w,\r\n            \"upscale_to_height\": upscaling_resize_h,\r\n            \"upscale_crop\": upscaling_crop,\r\n            \"upscaler_1_name\": extras_upscaler_1,\r\n            \"upscaler_2_name\": extras_upscaler_2,\r\n            \"upscaler_2_visibility\": extras_upscaler_2_visibility,\r\n        },\r\n        \"GFPGAN\": {\r\n            \"gfpgan_visibility\": gfpgan_visibility,\r\n        },\r\n        \"CodeFormer\": {\r\n            \"codeformer_visibility\": codeformer_visibility,\r\n            \"codeformer_weight\": codeformer_weight,\r\n        },\r\n    })\r\n\r\n    return run_postprocessing(extras_mode, image, image_folder, input_dir, output_dir, show_extras_results, *args, save_output=save_output)\r\n", "path": "modules/postprocessing.py"}]}