PitterTMYT commited on
Commit
283af5c
·
verified ·
1 Parent(s): 4f84ffe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -65
app.py CHANGED
@@ -1,88 +1,90 @@
1
- import gradio as gr
2
- import os, random
3
  import transformers
4
  import torch
 
5
 
 
6
  model_id = "yodayo-ai/nephra_v1.0"
7
 
 
8
  pipeline = transformers.pipeline(
9
- "text-generation",
10
- model=model_id,
11
- model_kwargs={"torch_dtype": torch.bfloat16},
12
- device_map="auto",
13
- )
14
-
15
- messages = [
16
- {"role": "system", "content": "You are to play the role of a Алекс - молодой и амбициозный приключенец, обладающий неутомимой энергией и жаждой новых открытий. Он всегда готов бросить вызов любым трудностям и стремится к познанию неизведанных мест."},
17
- {"role": "user", "content": "Hi there, how's your day?"},
18
- ]
19
-
20
- prompt = pipeline.tokenizer.apply_chat_template(
21
- messages,
22
- tokenize=False,
23
- add_generation_prompt=True
24
  )
25
 
26
- outputs = pipeline(
27
- prompt,
28
- max_new_tokens=512,
29
- eos_token_id=[
30
- pipeline.tokenizer.convert_tokens_to_ids("<|eot_id|>"),
31
- pipeline.tokenizer.eos_token_id,
32
- ],
33
- do_sample=True,
34
- temperature=1.12,
35
- min_p=0.075,
36
- )
37
- print(outputs[0]["generated_text"][len(prompt):])
38
- # Определение персонажей
39
  characters = [
40
- {"name": "Алекс",
41
- "description": "Алекс - молодой и амбициозный приключенец, обладающий неутомимой энергией и жаждой новых открытий. Он всегда готов бросить вызов любым трудностям и стремится к познанию неизведанных мест.",
42
- "traits": "смелый, энергичный, оптимистичный, решительный"},
43
-
44
- {"name": "Майя",
45
- "description": "Майя - мудрая и опытная волшебница, обладающая глубокими знаниями в магии и древних ритуалах. Она известна своим спокойствием, аналитическим умом и способностью находить решения в сложных ситуациях.",
46
- "traits": "спокойная, вдумчивая, интуитивная, внимательная"},
47
-
48
- {"name": "Виктор",
49
- "description": "Виктор - бывший воин, который оставил боевые подвиги ради поиска внутреннего мира и гармонии. Его жизненный опыт и стремление к справедливости делают его надежным другом и наставником.",
50
- "traits": "серьезный, рассудительный, справедливый, уравновешенный"}
 
 
 
 
51
  ]
52
 
53
- # Загрузка модели
54
- model_path = "model-q4_K.gguf"
55
- model = llama.load_model(model_path)
56
-
57
- def generate_response(character_name, prompt, max_length=100, temperature=0.7, top_p=0.85, repetition_penalty=1.1):
58
- # Поиск данных персонажа
59
  character = next((c for c in characters if c["name"] == character_name), None)
60
  if not character:
61
- return "Персонаж не найден."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- # Формирование текста запроса
64
- prompt_text = (f"Ты - {character_name}, {character['description']}. Черты характера: {character['traits']}. "
65
- f"В ответ на вопрос '{prompt}' {random.choice(['вдохновленно', 'с сомнением', 'с радостью', 'вдумчиво', 'с недоверием'])}. Пожалуйста, закончите ответ полностью.")
66
-
67
- # Генерация ответа
68
- response = model.generate(prompt_text, max_length=max_length, temperature=temperature, top_p=top_p, repetition_penalty=repetition_penalty)
69
- return response
70
 
71
- # Создание интерфейса Gradio
72
  iface = gr.Interface(
73
  fn=generate_response,
74
  inputs=[
75
- gr.inputs.Dropdown([c["name"] for c in characters], label="Выберите персонажа"),
76
- gr.inputs.Textbox(lines=2, placeholder="Введите ваш текст здесь..."),
77
- gr.inputs.Slider(20, 200, step=1, default=100, label="Максимальная длина"),
78
- gr.inputs.Slider(0.1, 1.0, step=0.1, default=0.7, label="Температура"),
79
- gr.inputs.Slider(0.1, 1.0, step=0.05, default=0.85, label="Top-p"),
80
- gr.inputs.Slider(1.0, 2.0, step=0.1, default=1.1, label="Штраф за повторение")
81
  ],
82
  outputs="text",
83
- title="LLM Model Demo",
84
- description="Введите текстовый запрос, чтобы сгенерировать ответ с помощью модели, основываясь на выбранном персонаже."
85
  )
86
 
87
  if __name__ == "__main__":
88
- iface.launch()
 
 
 
1
  import transformers
2
  import torch
3
+ import gradio as gr
4
 
5
+ # Model setup
6
  model_id = "yodayo-ai/nephra_v1.0"
7
 
8
+ # Load the model pipeline with the recommended settings
9
  pipeline = transformers.pipeline(
10
+ "text-generation",
11
+ model=model_id,
12
+ model_kwargs={"torch_dtype": torch.bfloat16},
13
+ device_map="auto",
 
 
 
 
 
 
 
 
 
 
 
14
  )
15
 
16
+ # Define characters
 
 
 
 
 
 
 
 
 
 
 
 
17
  characters = [
18
+ {
19
+ "name": "Alex",
20
+ "description": "Alex is a young and ambitious adventurer, full of energy and eager to discover new places. He is always ready to face any challenges and strives to explore the unknown.",
21
+ "traits": "brave, energetic, optimistic, determined"
22
+ },
23
+ {
24
+ "name": "Maya",
25
+ "description": "Maya is a wise and experienced sorceress, possessing deep knowledge of magic and ancient rituals. She is known for her calm demeanor, analytical mind, and ability to find solutions in difficult situations.",
26
+ "traits": "calm, thoughtful, intuitive, attentive"
27
+ },
28
+ {
29
+ "name": "Victor",
30
+ "description": "Victor is a former warrior who left behind his fighting days to seek inner peace and harmony. His life experience and sense of justice make him a reliable friend and mentor.",
31
+ "traits": "serious, judicious, fair, balanced"
32
+ }
33
  ]
34
 
35
+ # Function to generate response
36
+ def generate_response(character_name, user_input, max_length=100, temperature=1.12, min_p=0.075, repetition_penalty=1.1):
37
+ # Find the character
 
 
 
38
  character = next((c for c in characters if c["name"] == character_name), None)
39
  if not character:
40
+ return "Character not found."
41
+
42
+ # Prepare the message based on the selected character's personality and description
43
+ messages = [
44
+ {"role": "system", "content": f"You are {character_name}, {character['description']}. Personality traits: {character['traits']}."},
45
+ {"role": "user", "content": user_input},
46
+ ]
47
+
48
+ # Prepare the prompt using the chat template from the pipeline's tokenizer
49
+ prompt = pipeline.tokenizer.apply_chat_template(
50
+ messages,
51
+ tokenize=False,
52
+ add_generation_prompt=True
53
+ )
54
+
55
+ # Generate response using the pipeline
56
+ outputs = pipeline(
57
+ prompt,
58
+ max_new_tokens=max_length,
59
+ eos_token_id=[
60
+ pipeline.tokenizer.convert_tokens_to_ids(""),
61
+ pipeline.tokenizer.eos_token_id,
62
+ ],
63
+ do_sample=True,
64
+ temperature=temperature,
65
+ min_p=min_p,
66
+ repetition_penalty=repetition_penalty,
67
+ )
68
 
69
+ # Extract and return the generated response
70
+ generated_text = outputs[0]["generated_text"][len(prompt):].strip()
71
+ return generated_text
 
 
 
 
72
 
73
+ # Gradio Interface
74
  iface = gr.Interface(
75
  fn=generate_response,
76
  inputs=[
77
+ gr.Dropdown([c["name"] for c in characters], label="Choose a character"),
78
+ gr.Textbox(lines=2, placeholder="Enter your text here..."),
79
+ gr.Slider(20, 200, step=1, default=100, label="Max Length"),
80
+ gr.Slider(0.1, 1.0, step=0.1, default=1.12, label="Temperature"),
81
+ gr.Slider(0.01, 1.0, step=0.01, default=0.075, label="min-p"),
82
+ gr.Slider(1.0, 2.0, step=0.1, default=1.1, label="Repetition Penalty")
83
  ],
84
  outputs="text",
85
+ title="Nephra v1 LLM Roleplaying Chatbot",
86
+ description="Enter a text prompt to generate a response using the Nephra v1 model, based on the selected character."
87
  )
88
 
89
  if __name__ == "__main__":
90
+ iface.launch()