refoundd commited on
Commit
782a979
·
verified ·
1 Parent(s): ed1d673

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +69 -16
handler.py CHANGED
@@ -8,7 +8,54 @@ 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
- record=0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  class EndpointHandler:
13
  def __init__(self, path=""):
14
  self.pipe = FluxPipeline.from_pretrained(
@@ -22,9 +69,14 @@ class EndpointHandler:
22
  self.pipe.vae = torch.compile(
23
  self.pipe.vae, mode="max-autotune-no-cudagraphs",
24
  )
 
 
 
 
 
 
25
 
26
  def __call__(self, data: Dict[str, Any]) -> str:
27
- global record
28
  logger.info(f"Received incoming request with {data=}")
29
 
30
  if "inputs" in data and isinstance(data["inputs"], str):
@@ -36,8 +88,7 @@ class EndpointHandler:
36
  "Provided input body must contain either the key `inputs` or `prompt` with the"
37
  " prompt to use for the image generation, and it needs to be a non-empty string."
38
  )
39
- if prompt=="get_quene":
40
- return record
41
  parameters = data.pop("parameters", {})
42
 
43
  num_inference_steps = parameters.get("num_inference_steps", 28)
@@ -48,20 +99,22 @@ class EndpointHandler:
48
  # seed generator (seed cannot be provided as is but via a generator)
49
  seed = parameters.get("seed", 0)
50
  generator = torch.manual_seed(seed)
51
- record+=1
52
  start_time = time.time()
53
- time.sleep(6)
54
- # result = self.pipe( # type: ignore
55
- # prompt,
56
- # height=height,
57
- # width=width,
58
- # guidance_scale=guidance_scale,
59
- # num_inference_steps=num_inference_steps,
60
- # generator=generator,
61
- # ).images[0]
62
  end_time = time.time()
63
  time_taken = end_time - start_time
64
  print(f"Time taken: {time_taken:.2f} seconds")
65
- record-=1
 
 
 
 
66
 
67
- return record
 
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=6000)
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=""):
61
  self.pipe = FluxPipeline.from_pretrained(
 
69
  self.pipe.vae = torch.compile(
70
  self.pipe.vae, mode="max-autotune-no-cudagraphs",
71
  )
72
+ # ngrok
73
+ self.public_url = ngrok.connect(6000).public_url
74
+ # subprocess.Popen(['ngrok', 'http', '6000'], 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
 
82
  if "inputs" in data and isinstance(data["inputs"], str):
 
88
  "Provided input body must contain either the key `inputs` or `prompt` with the"
89
  " prompt to use for the image generation, and it needs to be a non-empty string."
90
  )
91
+
 
92
  parameters = data.pop("parameters", {})
93
 
94
  num_inference_steps = parameters.get("num_inference_steps", 28)
 
99
  # seed generator (seed cannot be provided as is but via a generator)
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