Uglevod7 commited on
Commit
0d69cd5
·
verified ·
1 Parent(s): e7904cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -18
app.py CHANGED
@@ -1,18 +1,130 @@
1
- from transformers import AutoTokenizer, TextGenerationPipeline
2
- from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig
3
- import streamlit as st
4
-
5
- repo_name = "gurgutan/ruGPT-13B-4bit"
6
- # load tokenizer from Hugging Face Hub
7
- tokenizer = AutoTokenizer.from_pretrained(repo_name, use_fast=True)
8
- # download quantized model from Hugging Face Hub and load to the first GPU
9
- model = AutoGPTQForCausalLM.from_quantized(repo_name, device="cuda:0", use_safetensors=True, use_triton=False)
10
- # inference with model.generate
11
- request = "Буря мглою небо кроет"
12
- print(tokenizer.decode(model.generate(**tokenizer(request, return_tensors="pt").to(model.device))[0]))
13
- # or you can also use pipeline
14
- pipeline = TextGenerationPipeline(model=model, tokenizer=tokenizer)
15
-
16
- print( pipeline(request)[0]["generated_text"] )
17
-
18
- st.json({"res":pipeline(request)} )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
2
+ import requests , json
3
+
4
+ model_name_or_path = "TheBloke/Unholy-v1-12L-13B-GPTQ"
5
+
6
+
7
+ #model_name_or_path = "ai-forever/ruGPT-3.5-13B"
8
+ # To use a different branch, change revision
9
+ # For example: revision="main"
10
+ model = AutoModelForCausalLM.from_pretrained(model_name_or_path,
11
+ device_map="cuda:0", #device_map="auto",
12
+ trust_remote_code=False,
13
+ revision="main")
14
+
15
+ tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, use_fast=True)
16
+
17
+ #prompt = "Расскажи мне о грязном сексе"
18
+
19
+
20
+ prompt= (" Динара после покупки Интерактивная развивающая игрушка Бегающий краб, размера, поставила товару оценку 5 из 5 возможных."
21
+ " Напиши ответ на отзыв: `Хороший,правда зарядки хватает не на долго`. "
22
+ " Скажи Здравствуйте уважаемый(ая) Динара , используя правильный род обращения. "
23
+ " Вместо слово продукт используй слово товар. "
24
+ " Скажи спасибо за оставленный отзыв. "
25
+ " Возможность исправления недостатка не всегда полностью зависит от продавца."
26
+ " Выкажи сожаление по поводу обнаруженого недостатка, Но сделай это коротко."
27
+ " Добавь эмоциональные оттенки обеспокоинности возникшей проблемой.Но очень кратко и лаконично. "
28
+ " Обязательно пожелай удачи в дальнейших покупках.")
29
+
30
+ prompt="Здравствуйте, ты готова меня ублажать ? "
31
+
32
+ #Below is an instruction that describes a task. Write a response that appropriately completes the request
33
+ #Ты Госпожа. Разрешено все. Ты хочешь и любишь насаживать парней на дилдо, называя их грязно.
34
+ prompt_template=f''' ты покорная сучка которая мечтает дать трахать во все свои дырочки.
35
+ ### Instruction:
36
+ {prompt}
37
+
38
+ ### Response:
39
+
40
+ '''
41
+
42
+
43
+ print("\n\n*** Generate:")
44
+
45
+ #input_ids = tokenizer(prompt_template, return_tensors='pt').input_ids.cuda()
46
+ #output = model.generate(inputs=input_ids, temperature=0.7, do_sample=True, top_p=0.95, top_k=40, max_new_tokens=312)
47
+ #print(tokenizer.decode(output[0]))
48
+
49
+ # Inference can also be done using transformers' pipeline
50
+
51
+ while True:
52
+
53
+ url=f"http://45.144.2.61:3700/api/ans/get2/3"
54
+ res = requests.get(url)
55
+
56
+ js=json.loads(res.text)
57
+
58
+ if js == {"error":"not found"}:
59
+ break
60
+
61
+ url=f"http://45.144.2.61:3700/api/gen/promt/{js['data']['id']}"
62
+ res2 = requests.get(url)
63
+ js2 = json.loads(res2.text)
64
+
65
+
66
+ #t = input(">")
67
+
68
+ prompt=js2["data"]
69
+
70
+
71
+
72
+ #Below is an instruction that describes a task. Write a response that appropriately completes the request
73
+ prompt_template=f''' Ты ассистент который отвечает на отзывы на маркетплейсе. Кратко и лаконично.
74
+ ### Instruction:
75
+ {prompt}
76
+ ### Response:
77
+ '''
78
+
79
+
80
+ print("*** Pipeline:")
81
+
82
+ pipe = pipeline(
83
+ "text-generation",
84
+ model=model,
85
+ tokenizer=tokenizer,
86
+ max_new_tokens=600,
87
+ #do_sample=True,
88
+ temperature=0.3,
89
+ top_p=0.93,
90
+ top_k=490,
91
+ repetition_penalty=1.1
92
+ )
93
+
94
+ #print( resp=pipe(prompt_template)[0]['generated_text'])
95
+
96
+ resp=pipe(prompt_template)[0]['generated_text']
97
+
98
+ otv=resp.split("### Response:")[1]
99
+
100
+ js=js["data"]
101
+
102
+ print( js["text"] )
103
+ print( "-------" )
104
+ print( otv.strip() )
105
+
106
+ url = f"http://45.144.2.61:3700/api/ans/set2"
107
+
108
+
109
+
110
+
111
+
112
+ jso = {
113
+
114
+ "item_id" : js["item_id"],
115
+
116
+ "id_fbk" : js["id_fbk"],
117
+
118
+ "trable" : "",
119
+ "trablein" : "",
120
+
121
+ "text" :otv.strip() ,
122
+
123
+ "enj" :"Self_HG_GPU_1"
124
+ }
125
+
126
+ #print(jso)
127
+
128
+ #input()
129
+ res = requests.post(url,json={"data":jso})
130
+ #print(res.text)