Spaces:
Sleeping
Sleeping
File size: 5,365 Bytes
a9b39d2 267da20 a9b39d2 fc5c61b a9b39d2 104d1d8 a9b39d2 267da20 a9b39d2 267da20 a9b39d2 104d1d8 a9b39d2 27403e1 a9b39d2 104d1d8 a9b39d2 30a6af1 a9b39d2 27403e1 a9b39d2 104d1d8 a9b39d2 30a6af1 a9b39d2 27403e1 a9b39d2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
from flask import Flask, request, Response, jsonify
from huggingface_hub import InferenceClient
from flask_cors import CORS
import json
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
summary_prompt = '<s>[INST]Ты ассистент. Отвечаешь на русском языке. Сформируй краткое изложение следующего текста: {}[/INST]'
def format_prompt(message, history):
prompt = "<s>"
for user_prompt, bot_response in history:
prompt += f"[INST] {user_prompt} [/INST]"
prompt += f" {bot_response}</s> "
prompt += f"[INST] {message} [/INST]"
return prompt
def split_text(text):
max_chars = 3500
sentences = text.split('.')
lines = []
for sentence in sentences:
lines.extend(sentence.split('\n'))
result = []
current_chunk = ''
for line in lines:
if len(current_chunk) + len(line) < max_chars:
current_chunk += line + '.'
else:
result.append(current_chunk.strip())
current_chunk = line + '.'
if current_chunk:
result.append(current_chunk.strip())
return result
def generate(
prompt, history=[], temperature=0, max_new_tokens=2000, top_p=0.95, repetition_penalty=1.0,
):
temperature = float(temperature)
if temperature < 1e-2:
temperature = 1e-2
top_p = float(top_p)
generate_kwargs = dict(
temperature=temperature,
max_new_tokens=max_new_tokens,
top_p=top_p,
repetition_penalty=repetition_penalty,
do_sample=True,
seed=42,
)
#formatted_prompt = format_prompt(prompt, history)
#stream = client.text_generation(prompt, **generate_kwargs, stream=True, details=False, return_full_text=False)
response = client.text_generation(prompt, **generate_kwargs, stream=False, details=False, return_full_text=False)
print(response)
return response
#output = ""
#for response in stream:
# yield response.token.text.encode('utf-8')
app = Flask(__name__)
CORS(app)
@app.route('/health', methods=['GET'])
def health():
return jsonify({"status": "ok"})
@app.route('/completion', methods=['POST'])
def completion_route():
data = request.get_json()
prompt = data.get('prompt', '')
#truncated_prompt = prompt[:32768]
return Response(generate(prompt[:52768]), content_type='text/plain; charset=utf-8', status=200, direct_passthrough=True)
@app.route('/getsummary', methods=['POST'])
def getsummary_route():
data = request.get_json()
text = data.get('text', '')
pages = split_text(text)
result = ''
for page in pages:
summary_prompt = f'''<s>[INST]выпиши из текста в виде трех списков 1.какие вопросы, темы обсуждались, 2. какие проблемы были озвучены 3. какие предложения были сформулированы: {page}[/INST]'''
response = generate(summary_prompt[:52000])
result = result + '\n'+response
return jsonify({'result': result})
@app.route('/cleantext', methods=['POST'])
def cleantext_route():
data = request.get_json()
text = data.get('text', '')
summary_prompt = f'''<s>[INST]Ты ассистент. Отвечаешь на русском языке. Сформируй краткое изложение следующего текста: {text}[/INST]'''
response = generate(summary_prompt[:52000])
return jsonify({'result': response})
@app.route('/getfollowup', methods=['POST'])
def getfollowup_route():
data = request.get_json()
text = data.get('text', '')
summary_prompt = f'''<s>[INST]Ты мой помощник. Ты отвечаешь только на РУССКОМ языке. Ты не отвечаешь на вопросы, не комментируешь,
не выражаешь эмоций, не выражаешь соображений по теме обращения. Ты выделяешь задачи из текста переписки и формируешь текст письма с поручениями сотрудникам для выполнения найденных задач.
Переписка: {text}[/INST]'''
response = generate(summary_prompt[:52000])
return jsonify({'result': response})
@app.route('/getagenda', methods=['POST'])
def getagenda_route():
data = request.get_json()
text = data.get('text', '')
summary_prompt = f'''<s>[INST]Ты мой помощник. Ты отвечаешь только на РУССКОМ языке. Ты не отвечаешь на вопросы, не комментируешь,
не выражаешь эмоций, не выражаешь соображений по теме обращения. Ты выделяешь выпросы из текста переписки, которые надо дорешать и задачи, выполнение которых надо проконтролировать. Результат выводишь в виде нумерованного списка.
Переписка: {text}[/INST]'''
response = generate(summary_prompt[:52000])
return jsonify({'result': response})
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=7860) |