YC-Chen commited on
Commit
8efcc66
1 Parent(s): bb3599e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -13
app.py CHANGED
@@ -156,22 +156,30 @@ with gr.Blocks() as demo:
156
  }
157
 
158
  start_time = time.time()
 
159
  with requests.post(API_URL, headers=HEADERS, data=json.dumps(data), stream=True, timeout=30) as r:
160
- for response in r.iter_lines():
161
- if len(response) > 0:
162
- text = response.decode()
163
- if text != "data: [DONE]":
164
- if text.startswith("data: "):
165
- text = text[5:]
166
- delta = json.loads(text)["choices"][0]["text"]
167
-
168
- if history[-1][1] is None:
169
- history[-1][1] = delta
170
- else:
171
- history[-1][1] += delta
 
 
 
 
 
 
 
172
 
173
- yield history
174
  if time.time() - start_time > MAX_SEC:
 
175
  break
176
 
177
  if history[-1][1].endswith('</s>'):
 
156
  }
157
 
158
  start_time = time.time()
159
+ keep_streaming = True
160
  with requests.post(API_URL, headers=HEADERS, data=json.dumps(data), stream=True, timeout=30) as r:
161
+ for line in r.iter_lines():
162
+ if line and keep_streaming:
163
+ assert r.status_code == 200
164
+ json_response = json.loads(line)
165
+
166
+ try:
167
+ if "fragment" not in json_response["result"]:
168
+ keep_streaming = False
169
+ break
170
+
171
+ delta = json_response["result"]["fragment"]["data"]["text"]
172
+ except Exception as e:
173
+ raise e
174
+
175
+ if history[-1][1] is None:
176
+ history[-1][1] = delta
177
+ else:
178
+ history[-1][1] += delta
179
+ yield history
180
 
 
181
  if time.time() - start_time > MAX_SEC:
182
+ keep_streaming = False
183
  break
184
 
185
  if history[-1][1].endswith('</s>'):