File size: 26,339 Bytes
c8f5641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b844a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dfa8ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0490dd
 
 
d8c7b69
68c48e6
2dfa8ab
68c48e6
c0490dd
fcb0cff
c0490dd
 
 
68c48e6
fcb0cff
 
2dfa8ab
 
 
3b844a5
fcb0cff
68c48e6
 
 
 
2dfa8ab
 
 
 
3b844a5
 
fcb0cff
 
c0490dd
 
68c48e6
c0490dd
 
68c48e6
c0490dd
fcb0cff
 
baa503f
 
68c48e6
baa503f
68c48e6
 
 
6a500ed
3b844a5
 
c8f5641
 
 
 
f81b3d1
e5efe2c
c0490dd
68c48e6
6a500ed
c8f5641
 
68c48e6
 
 
6a500ed
c8f5641
 
68c48e6
c0490dd
 
 
 
3b844a5
fcb0cff
c0490dd
 
bfd8827
 
fcb0cff
c0490dd
fcb0cff
c0490dd
 
bc47113
 
c0490dd
 
bfd8827
c0490dd
fcb0cff
c0490dd
 
 
 
fcb0cff
c0490dd
3b844a5
c8f5641
3b844a5
fcb0cff
c0490dd
fcb0cff
c0490dd
 
 
fcb0cff
c0490dd
 
fcb0cff
3b844a5
c0490dd
 
 
bc47113
c0490dd
 
 
 
 
 
 
fcb0cff
bfd8827
fcb0cff
 
 
2dfa8ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcb0cff
3b844a5
 
 
fcb0cff
3b844a5
 
 
 
 
 
bfd8827
3b844a5
2dfa8ab
3b844a5
 
 
 
 
 
 
2dfa8ab
3b844a5
 
 
 
 
c8f5641
bd26dca
c0490dd
68c48e6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
# import logging
# import random
# import warnings
# import gradio as gr
# import os
# import shutil
# import subprocess
# import spaces
# import torch
# import numpy as np
# from diffusers import FluxControlNetModel
# from diffusers.pipelines import FluxControlNetPipeline
# from PIL import Image
# from huggingface_hub import snapshot_download, login
# import io
# import base64
# from flask import Flask, request, jsonify
# from concurrent.futures import ThreadPoolExecutor
# from flask_cors import CORS
# import threading

# # Configure logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# app = Flask(__name__)
# CORS(app)

# # Function to check disk usage
# def check_disk_space():
#     result = subprocess.run(['df', '-h'], capture_output=True, text=True)
#     logger.info("Disk space usage:\n%s", result.stdout)

# # Function to clear Hugging Face cache
# def clear_huggingface_cache():
#     cache_dir = os.path.expanduser('~/.cache/huggingface')
#     if os.path.exists(cache_dir):
#         shutil.rmtree(cache_dir)  # Removes the entire cache directory
#         logger.info("Cleared Hugging Face cache at: %s", cache_dir)
#     else:
#         logger.info("No Hugging Face cache found.")

# # Check disk space
# check_disk_space()

# # Clear Hugging Face cache
# clear_huggingface_cache()

# # Add config to store base64 images
# app.config['image_outputs'] = {}

# # ThreadPoolExecutor for managing image processing threads
# executor = ThreadPoolExecutor()

# # Determine the device (GPU or CPU)
# if torch.cuda.is_available():
#     device = "cuda"
#     logger.info("CUDA is available. Using GPU.")
# else:
#     device = "cpu"
#     logger.info("CUDA is not available. Using CPU.")

# # Load model from Huggingface Hub
# huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
# if huggingface_token:
#     login(token=huggingface_token)
#     logger.info("Hugging Face token found and logged in.")
# else:
#     logger.warning("Hugging Face token not found in environment variables.")

# logger.info("Hugging Face token: %s", huggingface_token)

# # Download model using snapshot_download

# model_path = snapshot_download(
#         repo_id="black-forest-labs/FLUX.1-dev", 
#         repo_type="model", 
#         ignore_patterns=["*.md", "*..gitattributes"],
#         local_dir="FLUX.1-dev",
#         token=huggingface_token)
# logger.info("Model downloaded to: %s", model_path)

# # Load pipeline
# logger.info('Loading ControlNet model.')

# controlnet = FluxControlNetModel.from_pretrained(
#         "jasperai/Flux.1-dev-Controlnet-Upscaler", torch_dtype=torch.bfloat16
#     ).to(device)
# logger.info("ControlNet model loaded successfully.")

# logger.info('Loading pipeline.')

# pipe = FluxControlNetPipeline.from_pretrained(
#         model_path, controlnet=controlnet, torch_dtype=torch.bfloat16
#     ).to(device)
# logger.info("Pipeline loaded successfully.")

# MAX_SEED = 1000000
# MAX_PIXEL_BUDGET = 1024 * 1024


# @spaces.GPU
# def process_input(input_image, upscale_factor):
#     w, h = input_image.size
#     aspect_ratio = w / h
#     was_resized = False

#     # Resize if input size exceeds the maximum pixel budget
#     if w * h * upscale_factor**2 > MAX_PIXEL_BUDGET:
#         warnings.warn(f"Requested output image is too large. Resizing to fit within pixel budget.")
#         input_image = input_image.resize(
#             (
#                 int(aspect_ratio * MAX_PIXEL_BUDGET**0.5 // upscale_factor),
#                 int(MAX_PIXEL_BUDGET**0.5 // aspect_ratio // upscale_factor),
#             )
#         )
#         was_resized = True

#     # Adjust dimensions to be a multiple of 8
#     w, h = input_image.size
#     w = w - w % 8
#     h = h - h % 8

#     return input_image.resize((w, h)), was_resized

# @spaces.GPU
# def run_inference(process_id, input_image, upscale_factor, seed, num_inference_steps, controlnet_conditioning_scale):
#     logger.info("Processing inference for process_id: %s", process_id)
#     input_image, was_resized = process_input(input_image, upscale_factor)

#     # Rescale image for ControlNet processing
#     w, h = input_image.size
#     control_image = input_image.resize((w * upscale_factor, h * upscale_factor))

#     # Set the random generator for inference
#     generator = torch.Generator().manual_seed(seed)

#     # Perform inference using the pipeline
#     logger.info("Running pipeline for process_id: %s", process_id)
#     image = pipe(
#         prompt="",
#         control_image=control_image,
#         controlnet_conditioning_scale=controlnet_conditioning_scale,
#         num_inference_steps=num_inference_steps,
#         guidance_scale=3.5,
#         height=control_image.size[1],
#         width=control_image.size[0],
#         generator=generator,
#     ).images[0]

#     # Resize output image back to the original dimensions if needed
#     if was_resized:
#         original_size = (input_image.width * upscale_factor, input_image.height * upscale_factor)
#         image = image.resize(original_size)

#     # Convert the output image to base64
#     buffered = io.BytesIO()
#     image.save(buffered, format="JPEG")
#     image_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")

#     # Store the result in the shared dictionary
#     app.config['image_outputs'][process_id] = image_base64
#     logger.info("Inference completed for process_id: %s", process_id)

# @app.route('/infer', methods=['POST'])
# def infer():
#     # Check if the file was provided in the form-data
#     if 'input_image' not in request.files:
#         logger.error("No image file provided in request.")
#         return jsonify({
#             "status": "error",
#             "message": "No input_image file provided"
#         }), 400

#     # Get the uploaded image file from the request
#     file = request.files['input_image']

#     # Check if a file was uploaded
#     if file.filename == '':
#         logger.error("No selected file in form-data.")
#         return jsonify({
#             "status": "error",
#             "message": "No selected file"
#         }), 400

#     # Convert the image to Base64 for internal processing
#     input_image = Image.open(file)
#     buffered = io.BytesIO()
#     input_image.save(buffered, format="JPEG")

#     # Retrieve additional parameters from the request (if any)
#     seed = request.form.get("seed", 42, type=int)
#     randomize_seed = request.form.get("randomize_seed", 'true').lower() == 'true'
#     num_inference_steps = request.form.get("num_inference_steps", 28, type=int)
#     upscale_factor = request.form.get("upscale_factor", 4, type=int)
#     controlnet_conditioning_scale = request.form.get("controlnet_conditioning_scale", 0.6, type=float)

#     # Randomize seed if specified
#     if randomize_seed:
#         seed = random.randint(0, MAX_SEED)
#         logger.info("Seed randomized to: %d", seed)

#     # Create a unique process ID for this request
#     process_id = str(random.randint(1000, 9999))
#     logger.info("Process started with process_id: %s", process_id)

#     # Set the status to 'in_progress'
#     app.config['image_outputs'][process_id] = None

#     # Run the inference in a separate thread
#     executor.submit(run_inference, process_id, input_image, upscale_factor, seed, num_inference_steps, controlnet_conditioning_scale)

#     # Return the process ID
#     return jsonify({
#         "process_id": process_id,
#         "message": "Processing started"
#     })


# # Modify status endpoint to receive process_id in request body
# @app.route('/status', methods=['GET'])
# def status():
#     # Get the process_id from the query parameters
#     process_id = request.args.get('process_id')

#     # Check if process_id was provided
#     if not process_id:
#         logger.error("Process ID not provided in request.")
#         return jsonify({
#             "status": "error",
#             "message": "Process ID is required"
#         }), 400

#     # Check if the process_id exists in the dictionary
#     if process_id not in app.config['image_outputs']:
#         logger.error("Invalid process ID: %s", process_id)
#         return jsonify({
#             "status": "error",
#             "message": "Invalid process ID"
#         }), 404

#     # Check the status of the image processing
#     image_base64 = app.config['image_outputs'][process_id]
#     if image_base64 is None:
#         logger.info("Process ID %s is still in progress.", process_id)
#         return jsonify({
#             "status": "in_progress"
#         })
#     else:
#         logger.info("Process ID %s completed successfully.", process_id)
#         return jsonify({
#             "status": "completed",
#             "output_image": image_base64
#         })


# if __name__ == '__main__':
#     app.run(debug=True,host='0.0.0.0')





# import logging
# import random
# import warnings
# import gradio as gr
# import os
# import shutil
# import subprocess
# import torch
# import numpy as np
# from diffusers import FluxControlNetModel
# from diffusers.pipelines import FluxControlNetPipeline
# from PIL import Image
# from huggingface_hub import snapshot_download, login
# import io
# import base64
# import threading

# # Configure logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# # Function to check disk usage
# def check_disk_space():
#     result = subprocess.run(['df', '-h'], capture_output=True, text=True)
#     logger.info("Disk space usage:\n%s", result.stdout)

# # Function to clear Hugging Face cache
# def clear_huggingface_cache():
#     cache_dir = os.path.expanduser('~/.cache/huggingface')
#     if os.path.exists(cache_dir):
#         shutil.rmtree(cache_dir)  # Removes the entire cache directory
#         logger.info("Cleared Hugging Face cache at: %s", cache_dir)
#     else:
#         logger.info("No Hugging Face cache found.")

# # Check disk space
# check_disk_space()

# # Clear Hugging Face cache
# clear_huggingface_cache()

# # Add config to store base64 images
# image_outputs = {}

# # Determine the device (GPU or CPU)
# if torch.cuda.is_available():
#     device = "cuda"
#     logger.info("CUDA is available. Using GPU.")
# else:
#     device = "cpu"
#     logger.info("CUDA is not available. Using CPU.")

# # Load model from Huggingface Hub
# huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
# if huggingface_token:
#     login(token=huggingface_token)
#     logger.info("Hugging Face token found and logged in.")
# else:
#     logger.warning("Hugging Face token not found in environment variables.")

# # Download model using snapshot_download
# model_path = snapshot_download(
#     repo_id="black-forest-labs/FLUX.1-dev", 
#     repo_type="model", 
#     ignore_patterns=["*.md", "*..gitattributes"],
#     local_dir="FLUX.1-dev",
#     token=huggingface_token
# )
# logger.info("Model downloaded to: %s", model_path)

# # Load pipeline
# logger.info('Loading ControlNet model.')
# controlnet = FluxControlNetModel.from_pretrained(
#     "jasperai/Flux.1-dev-Controlnet-Upscaler", torch_dtype=torch.bfloat16
# ).to(device)
# logger.info("ControlNet model loaded successfully.")

# logger.info('Loading pipeline.')
# pipe = FluxControlNetPipeline.from_pretrained(
#     model_path, controlnet=controlnet, torch_dtype=torch.bfloat16
# ).to(device)
# logger.info("Pipeline loaded successfully.")

# MAX_SEED = 1000000
# MAX_PIXEL_BUDGET = 1024 * 1024

# def process_input(input_image, upscale_factor):
#     w, h = input_image.size
#     aspect_ratio = w / h
#     was_resized = False

#     # Resize if input size exceeds the maximum pixel budget
#     if w * h * upscale_factor**2 > MAX_PIXEL_BUDGET:
#         warnings.warn(f"Requested output image is too large. Resizing to fit within pixel budget.")
#         input_image = input_image.resize(
#             (
#                 int(aspect_ratio * MAX_PIXEL_BUDGET**0.5 // upscale_factor),
#                 int(MAX_PIXEL_BUDGET**0.5 // aspect_ratio // upscale_factor),
#             )
#         )
#         was_resized = True

#     # Adjust dimensions to be a multiple of 8
#     w, h = input_image.size
#     w = w - w % 8
#     h = h - h % 8

#     return input_image.resize((w, h)), was_resized

# def run_inference(input_image, upscale_factor, seed, num_inference_steps, controlnet_conditioning_scale):
#     logger.info("Running inference")
#     input_image, was_resized = process_input(input_image, upscale_factor)

#     # Rescale image for ControlNet processing
#     w, h = input_image.size
#     control_image = input_image.resize((w * upscale_factor, h * upscale_factor))

#     # Set the random generator for inference
#     generator = torch.Generator().manual_seed(seed)

#     # Perform inference using the pipeline
#     logger.info("Running pipeline")
#     image = pipe(
#         prompt="",
#         control_image=control_image,
#         controlnet_conditioning_scale=controlnet_conditioning_scale,
#         num_inference_steps=num_inference_steps,
#         guidance_scale=3.5,
#         height=control_image.size[1],
#         width=control_image.size[0],
#         generator=generator,
#     ).images[0]

#     # Resize output image back to the original dimensions if needed
#     if was_resized:
#         original_size = (input_image.width * upscale_factor, input_image.height * upscale_factor)
#         image = image.resize(original_size)

#     # Convert the output image to base64
#     buffered = io.BytesIO()
#     image.save(buffered, format="JPEG")
#     image_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")

#     logger.info("Inference completed")
#     return image_base64

# # Define Gradio interface
# def gradio_interface(input_image, upscale_factor=4, seed=42, num_inference_steps=28, controlnet_conditioning_scale=0.6):
#     if randomize_seed:
#         seed = random.randint(0, MAX_SEED)
#         logger.info("Seed randomized to: %d", seed)

#     # Run inference
#     output_image_base64 = run_inference(input_image, upscale_factor, seed, num_inference_steps, controlnet_conditioning_scale)
    
#     return Image.open(io.BytesIO(base64.b64decode(output_image_base64)))

# # Create Gradio interface
# iface = gr.Interface(
#     fn=gradio_interface,
#     inputs=[
#         gr.Image(type="pil", label="Input Image"),
#         gr.Slider(min=1, max=8, step=1, label="Upscale Factor"),
#         gr.Slider(min=0, max=MAX_SEED, step=1, label="Seed"),
#         gr.Slider(min=1, max=100, step=1, label="Inference Steps"),
#         gr.Slider(min=0.0, max=1.0, step=0.1, label="ControlNet Conditioning Scale")
#     ],
#     outputs=gr.Image(label="Output Image"),
#     title="ControlNet Image Upscaling",
#     description="Upload an image to upscale using the ControlNet model."
# )

# # Launch Gradio app
# if __name__ == '__main__':
#     iface.launch()


# import logging
# import random
# import warnings
# import gradio as gr
# import os
# import shutil
# import spaces
# import subprocess
# import torch
# import numpy as np
# from diffusers import FluxControlNetModel
# from diffusers.pipelines import FluxControlNetPipeline
# from PIL import Image
# from huggingface_hub import snapshot_download, login
# import io
# import base64
# from concurrent.futures import ThreadPoolExecutor

# # Configure logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# # ThreadPoolExecutor for managing image processing threads
# executor = ThreadPoolExecutor()

# # Determine the device (GPU or CPU)
# if torch.cuda.is_available():
#     device = "cuda"
#     logger.info("CUDA is available. Using GPU.")
# else:
#     device = "cpu"
#     logger.info("CUDA is not available. Using CPU.")

# # Load model from Huggingface Hub
# huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
# if huggingface_token:
#     login(token=huggingface_token)
#     logger.info("Hugging Face token found and logged in.")
# else:
#     logger.warning("Hugging Face token not found in environment variables.")

# # Download model using snapshot_download
# model_path = snapshot_download(
#     repo_id="black-forest-labs/FLUX.1-dev",
#     repo_type="model",
#     ignore_patterns=["*.md", "*..gitattributes"],
#     local_dir="FLUX.1-dev",
#     token=huggingface_token
# )
# logger.info("Model downloaded to: %s", model_path)

# # Load pipeline
# logger.info('Loading ControlNet model.')
# controlnet = FluxControlNetModel.from_pretrained(
#     "jasperai/Flux.1-dev-Controlnet-Upscaler", torch_dtype=torch.bfloat16
# ).to(device)
# logger.info("ControlNet model loaded successfully.")

# logger.info('Loading pipeline.')
# pipe = FluxControlNetPipeline.from_pretrained(
#     model_path, controlnet=controlnet, torch_dtype=torch.bfloat16
# ).to(device)
# logger.info("Pipeline loaded successfully.")

# MAX_SEED = 1000000
# MAX_PIXEL_BUDGET = 1024 * 1024

# @spaces.GPU
# def process_input(input_image, upscale_factor):
#     w, h = input_image.size
#     aspect_ratio = w / h
#     was_resized = False

#     # Resize if input size exceeds the maximum pixel budget
#     if w * h * upscale_factor**2 > MAX_PIXEL_BUDGET:
#         warnings.warn(f"Requested output image is too large. Resizing to fit within pixel budget.")
#         input_image = input_image.resize(
#             (
#                 int(aspect_ratio * MAX_PIXEL_BUDGET**0.5 // upscale_factor),
#                 int(MAX_PIXEL_BUDGET**0.5 // aspect_ratio // upscale_factor),
#             )
#         )
#         was_resized = True

#     # Adjust dimensions to be a multiple of 8
#     w, h = input_image.size
#     w = w - w % 8
#     h = h - h % 8

#     return input_image.resize((w, h)), was_resized
    

# @spaces.GPU
# def run_inference(input_image, upscale_factor, seed, num_inference_steps, controlnet_conditioning_scale):
#     logger.info("Processing inference.")
#     input_image, was_resized = process_input(input_image, upscale_factor)

#     # Rescale image for ControlNet processing
#     w, h = input_image.size
#     control_image = input_image.resize((w * upscale_factor, h * upscale_factor))

#     # Set the random generator for inference
#     generator = torch.Generator().manual_seed(seed)

#     # Perform inference using the pipeline
#     logger.info("Running pipeline.")
#     image = pipe(
#         prompt="",
#         control_image=control_image,
#         controlnet_conditioning_scale=controlnet_conditioning_scale,
#         num_inference_steps=num_inference_steps,
#         guidance_scale=3.5,
#         height=control_image.size[1],
#         width=control_image.size[0],
#         generator=generator,
#     ).images[0]

#     # Resize output image back to the original dimensions if needed
#     if was_resized:
#         original_size = (input_image.width * upscale_factor, input_image.height * upscale_factor)
#         image = image.resize(original_size)

#     return image

# def run_gradio_app():
#     with gr.Blocks() as app:
#         gr.Markdown("## Image Upscaler using ControlNet")

#         # Define the inputs and outputs
#         input_image = gr.Image(type="pil", label="Input Image")
#         upscale_factor = gr.Slider(minimum=1, maximum=8, step=1, label="Upscale Factor")
#         seed = gr.Slider(minimum=0, maximum=100, step=1, label="Seed")
#         num_inference_steps = gr.Slider(minimum=1, maximum=100, step=1, label="Inference Steps")
#         controlnet_conditioning_scale = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label="ControlNet Conditioning Scale")

#         output_image = gr.Image(type="pil", label="Output Image")

#         # Create a button to trigger the processing
#         submit_button = gr.Button("Upscale Image")

#         # Define the function to run when the button is clicked
#         submit_button.click(run_inference, 
#                              inputs=[input_image, upscale_factor, seed, num_inference_steps, controlnet_conditioning_scale], 
#                              outputs=output_image)

#     app.launch()

# if __name__ == "__main__":
#     run_gradio_app()




import logging
import random
import warnings
import gradio as gr
import os
import shutil,spaces
import subprocess
import torch
import numpy as np
from diffusers import FluxControlNetModel
from diffusers.pipelines import FluxControlNetPipeline
from PIL import Image
from huggingface_hub import snapshot_download, login
import io
import base64
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from concurrent.futures import ThreadPoolExecutor

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# FastAPI app for image processing
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])

# ThreadPoolExecutor for managing image processing threads
executor = ThreadPoolExecutor()

# Determine the device (GPU or CPU)
if torch.cuda.is_available():
    device = "cuda"
    logger.info("CUDA is available. Using GPU.")
else:
    device = "cpu"
    logger.info("CUDA is not available. Using CPU.")

# Load model from Huggingface Hub
huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
if huggingface_token:
    login(token=huggingface_token)
    logger.info("Hugging Face token found and logged in.")
else:
    logger.warning("Hugging Face token not found in environment variables.")

# Download model using snapshot_download
model_path = snapshot_download(
    repo_id="black-forest-labs/FLUX.1-dev",
    repo_type="model",
    ignore_patterns=["*.md", "*..gitattributes"],
    local_dir="FLUX.1-dev",
    token=huggingface_token
)
logger.info("Model downloaded to: %s", model_path)

# Load pipeline
logger.info('Loading ControlNet model.')
controlnet = FluxControlNetModel.from_pretrained(
    "jasperai/Flux.1-dev-Controlnet-Upscaler", torch_dtype=torch.bfloat16
).to(device)
logger.info("ControlNet model loaded successfully.")

logger.info('Loading pipeline.')
pipe = FluxControlNetPipeline.from_pretrained(
    model_path, controlnet=controlnet, torch_dtype=torch.bfloat16
).to(device)
logger.info("Pipeline loaded successfully.")

MAX_SEED = 1000000
MAX_PIXEL_BUDGET = 1024 * 1024

@spaces.GPU
def process_input(input_image, upscale_factor):
    w, h = input_image.size
    aspect_ratio = w / h
    was_resized = False

    # Resize if input size exceeds the maximum pixel budget
    if w * h * upscale_factor**2 > MAX_PIXEL_BUDGET:
        warnings.warn(f"Requested output image is too large. Resizing to fit within pixel budget.")
        input_image = input_image.resize(
            (
                int(aspect_ratio * MAX_PIXEL_BUDGET**0.5 // upscale_factor),
                int(MAX_PIXEL_BUDGET**0.5 // aspect_ratio // upscale_factor),
            )
        )
        was_resized = True

    # Adjust dimensions to be a multiple of 8
    w, h = input_image.size
    w = w - w % 8
    h = h - h % 8

    return input_image.resize((w, h)), was_resized

@spaces.GPU
def run_inference(input_image, upscale_factor, seed, num_inference_steps, controlnet_conditioning_scale):
    logger.info("Processing inference.")
    input_image, was_resized = process_input(input_image, upscale_factor)

    # Rescale image for ControlNet processing
    w, h = input_image.size
    control_image = input_image.resize((w * upscale_factor, h * upscale_factor))

    # Set the random generator for inference
    generator = torch.Generator().manual_seed(seed)

    # Perform inference using the pipeline
    logger.info("Running pipeline.")
    image = pipe(
        prompt="",
        control_image=control_image,
        controlnet_conditioning_scale=controlnet_conditioning_scale,
        num_inference_steps=num_inference_steps,
        guidance_scale=3.5,
        height=control_image.size[1],
        width=control_image.size[0],
        generator=generator,
    ).images[0]

    # Resize output image back to the original dimensions if needed
    if was_resized:
        original_size = (input_image.width * upscale_factor, input_image.height * upscale_factor)
        image = image.resize(original_size)

    # Convert the output image to base64
    buffered = io.BytesIO()
    image.save(buffered, format="JPEG")
    image_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")

    return image_base64

@app.post("/infer")
async def infer(input_image: UploadFile = File(...), 
                 upscale_factor: int = 4, 
                 seed: int = 42, 
                 num_inference_steps: int = 28, 
                 controlnet_conditioning_scale: float = 0.6):
    logger.info("Received request for inference.")
    
    # Read the uploaded image
    contents = await input_image.read()
    image = Image.open(io.BytesIO(contents))

    # Run inference in a separate thread
    base64_image = await executor.submit(run_inference, image, upscale_factor, seed, num_inference_steps, controlnet_conditioning_scale)

    return JSONResponse(content={"base64_image": base64_image})

def run_gradio_app():
    with gr.Blocks() as app:
        gr.Markdown("## Image Upscaler using ControlNet")

        # Define the inputs and outputs
        input_image = gr.Image(type="pil", label="Input Image")
        upscale_factor = gr.Slider(minimum=1, maximum=8, step=1, label="Upscale Factor")
        seed = gr.Slider(minimum=0, maximum=100, step=1, label="Seed")
        num_inference_steps = gr.Slider(minimum=1, maximum=100, step=1, label="Inference Steps")
        controlnet_conditioning_scale = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, label="ControlNet Conditioning Scale")

        output_image = gr.Image(type="pil", label="Output Image")
        output_base64 = gr.Textbox(label="Base64 String", interactive=False)

        # Create a button to trigger the processing
        submit_button = gr.Button("Upscale Image")

        # Define the function to run when the button is clicked
        submit_button.click(run_inference, 
                             inputs=[input_image, upscale_factor, seed, num_inference_steps, controlnet_conditioning_scale], 
                             outputs=[output_image, output_base64])

    app.launch()

if __name__ == "__main__":
    run_gradio_app()