import os import gradio as gr import clueai import torch from transformers import T5Tokenizer, T5ForConditionalGeneration tokenizer = T5Tokenizer.from_pretrained("huolongguo10/HR_Chat") model = T5ForConditionalGeneration.from_pretrained("huolongguo10/HR_Chat") # 使用 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) base_info = "用户:你是谁?\n小元:我是huolongguo10助手智能助手。\n" def preprocess(text): text = f"{base_info}{text}" text = text.replace("\n", "\\n").replace("\t", "\\t") return text def postprocess(text): return text.replace("\\n", "\n").replace("\\t", "\t").replace('%20',' ')#.replace(" ", " ") generate_config = {'do_sample': True, 'top_p': 0.9, 'top_k': 50, 'temperature': 0.7, 'num_beams': 1, 'max_length': 1024, 'min_length': 3, 'no_repeat_ngram_size': 5, 'length_penalty': 0.6, 'return_dict_in_generate': True, 'output_scores': True} def answer(text, sample=True, top_p=0.9, temperature=0.7): '''sample:是否抽样。生成任务,可以设置为True; top_p:0-1之间,生成的内容越多样''' text = preprocess(text) encoding = tokenizer(text=[text], truncation=True, padding=True, max_length=1024, return_tensors="pt").to(device) if not sample: out = model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_new_tokens=1024, num_beams=1, length_penalty=0.6) else: out = model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_new_tokens=1024, do_sample=True, top_p=top_p, temperature=temperature, no_repeat_ngram_size=12) #out=model.generate(**encoding, **generate_config) out_text = tokenizer.batch_decode(out["sequences"], skip_special_tokens=True) return postprocess(out_text[0]) def clear_session(): return '', None def chatyuan_bot(input, history): history = history or [] if len(history) > 5: history = history[-5:] context = "\n".join([f"用户:{input_text}\n小元:{answer_text}" for input_text, answer_text in history]) #print(context) input_text = context + "\n用户:" + input + "\n小元:" input_text = input_text.strip() output_text = answer(input_text) print("open_model".center(20, "=")) print(f"{input_text}\n{output_text}") #print("="*20) history.append((input, output_text)) #print(history) return history, history def chatyuan_bot_regenerate(input, history): history = history or [] if history: input=history[-1][0] history=history[:-1] if len(history) > 5: history = history[-5:] context = "\n".join([f"用户:{input_text}\n小元:{answer_text}" for input_text, answer_text in history]) #print(context) input_text = context + "\n用户:" + input + "\n小元:" input_text = input_text.strip() output_text = answer(input_text) print("open_model".center(20, "=")) print(f"{input_text}\n{output_text}") history.append((input, output_text)) #print(history) return history, history block = gr.Blocks() with block as demo: gr.Markdown("""