refoundd commited on
Commit
b319cc8
·
verified ·
1 Parent(s): a9957cd

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +68 -11
handler.py CHANGED
@@ -6,7 +6,55 @@ from diffusers import FluxPipeline
6
  from huggingface_inference_toolkit.logging import logger
7
  from para_attn.first_block_cache.diffusers_adapters import apply_cache_on_pipe
8
  import time
 
 
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  class EndpointHandler:
12
  def __init__(self, path=""):
@@ -21,8 +69,13 @@ class EndpointHandler:
21
  self.pipe.vae = torch.compile(
22
  self.pipe.vae, mode="max-autotune-no-cudagraphs",
23
  )
24
- self.record=0
 
 
 
 
25
 
 
26
  def __call__(self, data: Dict[str, Any]) -> str:
27
  logger.info(f"Received incoming request with {data=}")
28
 
@@ -47,17 +100,21 @@ class EndpointHandler:
47
  seed = parameters.get("seed", 0)
48
  generator = torch.manual_seed(seed)
49
  start_time = time.time()
50
- # result = self.pipe( # type: ignore
51
- # prompt,
52
- # height=height,
53
- # width=width,
54
- # guidance_scale=guidance_scale,
55
- # num_inference_steps=num_inference_steps,
56
- # generator=generator,
57
- # ).images[0]
58
  end_time = time.time()
59
  time_taken = end_time - start_time
60
  print(f"Time taken: {time_taken:.2f} seconds")
61
- self.record+=1
 
 
 
 
62
 
63
- return self.record
 
6
  from huggingface_inference_toolkit.logging import logger
7
  from para_attn.first_block_cache.diffusers_adapters import apply_cache_on_pipe
8
  import time
9
+ import uuid
10
+ from huggingface_hub import HfApi
11
 
12
+ from pyngrok import ngrok
13
+ import subprocess
14
+ from fastapi import FastAPI
15
+ from fastapi.responses import FileResponse
16
+ import uvicorn
17
+ import threading
18
+
19
+ image_directory='./images'
20
+ if not os.path.exists(image_directory):
21
+ os.makedirs(image_directory)
22
+
23
+ app = FastAPI()
24
+
25
+ @app.get("/images/{image_name}")
26
+ async def get_image(image_name: str):
27
+ image_path = os.path.join(image_directory, image_name)
28
+
29
+ if os.path.exists(image_path):
30
+ return FileResponse(image_path)
31
+ else:
32
+ return {"error": "Image not found"}
33
+
34
+ def run_uvicorn():
35
+ uvicorn.run(app, host="127.0.0.1", port=5000)
36
+
37
+ uvicorn_thread = threading.Thread(target=run_uvicorn)
38
+ uvicorn_thread.daemon = True
39
+ uvicorn_thread.start()
40
+
41
+ authtoken = "2cvqFKWc1eb9b0aN7pRLDUBfEtC_2FUehxFL8CAKXRkW3Hfjo"
42
+ commands = [
43
+ # "snap install ngrok",
44
+ f"ngrok config add-authtoken {authtoken}"
45
+ ]
46
+ for command in commands:
47
+ try:
48
+ subprocess.run(command, shell=True, check=True)
49
+ logger.info(f"SUCCESS CMD: {command}")
50
+ except subprocess.CalledProcessError as e:
51
+ logger.info(f"Failed CMD: {e}")
52
+ def run_ngrok():
53
+ subprocess.run(["ngrok", "http", "5000"])
54
+ ngrok_thread = threading.Thread(target=run_ngrok)
55
+ ngrok_thread.daemon = True
56
+ ngrok_thread.start()
57
+ logger.info("ngrok is running in the background")
58
 
59
  class EndpointHandler:
60
  def __init__(self, path=""):
 
69
  self.pipe.vae = torch.compile(
70
  self.pipe.vae, mode="max-autotune-no-cudagraphs",
71
  )
72
+ # ngrok
73
+ self.public_url = ngrok.connect(5000).public_url
74
+ # subprocess.Popen(['ngrok', 'http', '5000'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
75
+
76
+ logger.info("Ngrok is running in the background.")
77
 
78
+
79
  def __call__(self, data: Dict[str, Any]) -> str:
80
  logger.info(f"Received incoming request with {data=}")
81
 
 
100
  seed = parameters.get("seed", 0)
101
  generator = torch.manual_seed(seed)
102
  start_time = time.time()
103
+ result = self.pipe( # type: ignore
104
+ prompt,
105
+ height=height,
106
+ width=width,
107
+ guidance_scale=guidance_scale,
108
+ num_inference_steps=num_inference_steps,
109
+ generator=generator,
110
+ ).images[0]
111
  end_time = time.time()
112
  time_taken = end_time - start_time
113
  print(f"Time taken: {time_taken:.2f} seconds")
114
+ filename = f"{uuid.uuid4()}.png"
115
+ image_path = f"/images/{filename}"
116
+
117
+ result.save(image_path)
118
+ image_url = f"{self.public_url+image_path}"
119
 
120
+ return image_url