feat: add loading spinner to gpc for API request status updates

This commit is contained in:
Arthur K. 2025-01-09 21:07:58 +03:00
parent a101c908ca
commit 365e0feddc
Signed by: wzray
GPG key ID: B97F30FDC4636357

View file

@ -3,7 +3,12 @@
import os import os
import subprocess import subprocess
import sys import sys
from typing import Literal
import requests import requests
import time
import threading
state: Literal["loading", "done", "fail"] = "loading"
def die(r: str): def die(r: str):
print(r, file=sys.stderr) print(r, file=sys.stderr)
@ -17,6 +22,16 @@ def strip_equal(msg: str, substring: str, n_max: int) -> str:
def cleanup_string(s: str) -> str: def cleanup_string(s: str) -> str:
return strip_equal(s.replace('\n','').strip(), '`', 4) return strip_equal(s.replace('\n','').strip(), '`', 4)
def spin(text: str):
interval = 80
spinner = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
i = 0
while state == "loading":
i = (i + 1) % len(spinner)
print(f"\r{spinner[i]} {text}", end=' ')
time.sleep(interval / 1000)
symbol = "✔️" if state == "done" else "❌"
print(f"\r{symbol} {text}")
# globals # globals
@ -61,6 +76,9 @@ for arg in argv:
if arg == "-n": if arg == "-n":
N = int(next(argv)) N = int(next(argv))
thread = threading.Thread(target = spin, args = ['Generating...'])
thread.start()
r = requests.post("https://api.openai.com/v1/chat/completions", headers={'Authorization': f'Bearer {KEY}'}, json = { r = requests.post("https://api.openai.com/v1/chat/completions", headers={'Authorization': f'Bearer {KEY}'}, json = {
"model": "gpt-4o-mini", "model": "gpt-4o-mini",
"messages": [ "messages": [
@ -95,8 +113,13 @@ r = requests.post("https://api.openai.com/v1/chat/completions", headers={'Author
}) })
if r.status_code != 200: if r.status_code != 200:
state = "fail"
thread.join()
die(f"status code: {r.status_code}\n{r.text}") die(f"status code: {r.status_code}\n{r.text}")
state = "done"
thread.join()
choices = '# ' + '\n# '.join(map(lambda x: cleanup_string(x['message']['content']), r.json()['choices'])) choices = '# ' + '\n# '.join(map(lambda x: cleanup_string(x['message']['content']), r.json()['choices']))
fd = os.memfd_create("file.txt") fd = os.memfd_create("file.txt")