zdou0830 commited on
Commit
f444299
1 Parent(s): cecc788
Files changed (1) hide show
  1. main.py +34 -1
main.py CHANGED
@@ -10,6 +10,36 @@ response = requests.get("https://git.io/JJkYN")
10
  labels = response.text.split("\n")
11
 
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  def predict(inp):
14
  inp = transforms.ToTensor()(inp).unsqueeze(0)
15
  with torch.no_grad():
@@ -25,7 +55,10 @@ def run():
25
  outputs=gr.outputs.Label(num_top_classes=3),
26
  )
27
 
28
- demo.launch(server_name="0.0.0.0", server_port=7861)
 
 
 
29
 
30
 
31
  if __name__ == "__main__":
 
10
  labels = response.text.split("\n")
11
 
12
 
13
+ INITIAL_PORT_VALUE = int(os.getenv("GRADIO_SERVER_PORT", "7860"))
14
+ TRY_NUM_PORTS = int(os.getenv("GRADIO_NUM_PORTS", "100"))
15
+ LOCALHOST_NAME = os.getenv("GRADIO_SERVER_NAME", "127.0.0.1")
16
+ GRADIO_API_SERVER = "https://api.gradio.app/v1/tunnel-request"
17
+
18
+
19
+
20
+ def get_first_available_port(initial: int, final: int) -> int:
21
+ """
22
+ Gets the first open port in a specified range of port numbers
23
+ Parameters:
24
+ initial: the initial value in the range of port numbers
25
+ final: final (exclusive) value in the range of port numbers, should be greater than `initial`
26
+ Returns:
27
+ port: the first open port in the range
28
+ """
29
+ for port in range(initial, final):
30
+ try:
31
+ s = socket.socket() # create a socket object
32
+ s.bind((LOCALHOST_NAME, port)) # Bind to the port
33
+ s.close()
34
+ return port
35
+ except OSError:
36
+ pass
37
+ raise OSError(
38
+ "All ports from {} to {} are in use. Please close a port.".format(
39
+ initial, final
40
+ )
41
+ )
42
+
43
  def predict(inp):
44
  inp = transforms.ToTensor()(inp).unsqueeze(0)
45
  with torch.no_grad():
 
55
  outputs=gr.outputs.Label(num_top_classes=3),
56
  )
57
 
58
+ demo.launch(server_name=LOCALHOST_NAME, server_port=get_first_available_port(
59
+ INITIAL_PORT_VALUE, INITIAL_PORT_VALUE + TRY_NUM_PORTS
60
+ )
61
+ #demo.launch(server_name="0.0.0.0", server_port=7861)
62
 
63
 
64
  if __name__ == "__main__":