vtrv.vls commited on
Commit
623a39b
1 Parent(s): 8873b6c
Files changed (2) hide show
  1. app.py +5 -3
  2. utils.py +67 -0
app.py CHANGED
@@ -1,8 +1,10 @@
1
  import gradio as gr
 
2
  import os
3
 
4
- def greet(name):
5
- return "Hello " + name + os.getenv('GIGACHAT_API_TOKEN')[-4:] + "!!"
 
6
 
7
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
8
  demo.launch()
 
1
  import gradio as gr
2
+ from utils import generate
3
  import os
4
 
5
+ def gen(content):
6
+ res = generate(content,'auth_token.json')
7
+ return res
8
 
9
+ demo = gr.Interface(fn=gen, inputs="text", outputs="text")
10
  demo.launch()
utils.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ import os
4
+ from datetime import datetime, timedelta
5
+
6
+
7
+ def gen_auth_token():
8
+ url = "https://ngw.devices.sberbank.ru:9443/api/v2/oauth"
9
+
10
+ payload='scope=GIGACHAT_API_CORP'
11
+ headers = {
12
+ 'Content-Type': 'application/x-www-form-urlencoded',
13
+ 'Accept': 'application/json',
14
+ 'RqUID': '1b519047-0ee9-4b63-8599-e5ffc9c77e72',
15
+ 'Authorization': os.getenv('GIGACHAT_API_TOKEN')
16
+ }
17
+
18
+ response = requests.request("POST", url, headers=headers, data=payload, verify=False)
19
+
20
+ with open('auth_token.json', 'w') as f:
21
+ json.dump(json.loads(response.text), f, ensure_ascii=False)
22
+
23
+
24
+ def get_text(content='Привет!', auth_token=None):
25
+ url = "https://gigachat.devices.sberbank.ru/api/v1/chat/completions"
26
+
27
+ payload = json.dumps({
28
+ "model": "GigaChat",
29
+ "messages": [
30
+ {
31
+ "role": "user",
32
+ "content": content
33
+ }
34
+ ],
35
+ "temperature": 1,
36
+ "top_p": 0.1,
37
+ "n": 1,
38
+ "stream": False,
39
+ "max_tokens": 512,
40
+ "repetition_penalty": 1
41
+ })
42
+ headers = {
43
+ 'Content-Type': 'application/json',
44
+ 'Accept': 'application/json',
45
+ 'Authorization': f'Bearer {auth_token}'
46
+ }
47
+
48
+ response = requests.request("POST", url, headers=headers, data=payload, verify=False)
49
+
50
+ return json.loads(response.text)
51
+
52
+
53
+ def generate(content='Привет!', auth_file=None):
54
+ if auth_file is None or not os.path.isfile(auth_file):
55
+ gen_auth_token()
56
+
57
+ with open(auth_file) as f:
58
+ auth_token = json.load(f)
59
+
60
+ if datetime.fromtimestamp(auth_token['expires_at']/1000) <= datetime.now() - timedelta(seconds=60):
61
+ gen_auth_token()
62
+ with open(auth_file) as f:
63
+ auth_token = json.load(f)
64
+
65
+ resp = get_text(content, auth_token['access_token'])
66
+
67
+ return resp["choices"][0]["message"]["content"]