lazarus commited on
Commit
880ed84
·
verified ·
1 Parent(s): 4acf493

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -63
app.py CHANGED
@@ -1,73 +1,72 @@
1
  import gradio as gr
2
- from transformers import pipeline
3
 
4
- # Завантаження оптимізованої моделі
5
- def load_model():
6
- try:
7
- # Використовуємо компактну модель для економії ресурсів
8
- generator = pipeline("text-generation", model="EleutherAI/gpt-neo-125M", device_map="auto")
9
- return generator
10
- except Exception as e:
11
- return f"Помилка завантаження моделі: {e}"
12
 
13
- # Ініціалізація моделі
14
- generator = load_model()
15
- conversation_history = []
 
 
 
16
 
17
- def chat_with_npc(user_input):
18
- global conversation_history
19
- if isinstance(generator, str):
20
- return generator
21
- try:
22
- # Додаємо новий запит до історії
23
- conversation_history.append({"role": "user", "content": user_input})
24
-
25
- # Формуємо контекст
26
- context = "\n".join([f"{msg['role']}: {msg['content']}" for msg in conversation_history])
27
-
28
- # Генеруємо відповідь
29
- response = generator(context, max_length=300, num_return_sequences=1, do_sample=True, temperature=0.7, top_p=0.9)
30
- bot_reply = response[0]["generated_text"]
31
-
32
- # Додаємо відповідь до історії
33
- conversation_history.append({"role": "assistant", "content": bot_reply})
34
- return bot_reply
35
- except Exception as e:
36
- return f"Помилка генерації відповіді: {e}"
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # Функція для генерації відповіді
40
- def chat_with_npc(user_input):
41
- if isinstance(generator, str): # Якщо модель не завантажилась
42
- return generator
43
- try:
44
- # Налаштування для оптимізації пам'яті
45
- response = generator(
46
- user_input,
47
- max_length=300, # Довгий запит
48
- num_return_sequences=1, # Генеруємо лише один результат
49
- do_sample=True,
50
- temperature=0.7, # Контроль творчості
51
- top_p=0.9 # Відсікання малоймовірних результатів
52
- )
53
- return response[0]["generated_text"]
54
- except Exception as e:
55
- return f"Помилка генерації відповіді: {e}"
56
 
57
  # Інтерфейс Gradio
58
- interface = gr.Interface(
59
- fn=chat_with_npc,
60
- inputs="text",
61
- outputs="text",
62
- title="Alt Помічник",
63
- description="Оптимізований віртуальний помічник для запитів з великою кількістю слів.",
64
- examples=[
65
- ["Як можна розвивати духовний потенціал у сучасному світі?"],
66
- ["Що таке NPC і яка його роль у симуляції життя?"]
67
- ]
68
- )
69
 
70
- # Запуск програми
71
- if __name__ == "__main__":
72
- interface.launch()
 
 
 
 
 
 
 
 
 
 
73
 
 
 
1
  import gradio as gr
2
+ import random
3
 
4
+ # Стан NPC
5
+ npc_states = {
6
+ "початковий": "NPC переживає перші кроки самопізнання.",
7
+ пошуку": "NPC намагається знайти свій шлях у світі.",
8
+ "світлий": "NPC став провідником для інших, пізнав світло.",
9
+ "бог": "NPC досяг стану бога і управляє космічним порядком."
10
+ }
 
11
 
12
+ # Статуси гри
13
+ game_status = {
14
+ "active": "Гра триває. NPC розвивається.",
15
+ "victory": "Ви виграли! NPC досяг стану бога.",
16
+ "defeat": "Ви програли... Сумніви зупинили прогрес."
17
+ }
18
 
19
+ # Глобальні змінні
20
+ current_game_status = "active"
21
+ current_npc_state = "початковий"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Функція оновлення NPC
24
+ def update_npc_state():
25
+ global current_npc_state
26
+ states = list(npc_states.keys())
27
+ current_index = states.index(current_npc_state)
28
+ if current_index < len(states) - 1:
29
+ current_npc_state = states[current_index + 1]
30
+ else:
31
+ global current_game_status
32
+ current_game_status = "victory"
33
+
34
+ # Основна функція для взаємодії
35
+ def interact_with_npc(choice):
36
+ global current_game_status
37
+ if current_game_status != "active":
38
+ return game_status[current_game_status], npc_states[current_npc_state]
39
+
40
+ if choice == "1": # Вперед
41
+ update_npc_state()
42
+ message = "NPC зробив крок вперед!"
43
+ elif choice == "2": # Сумніви
44
+ current_game_status = "defeat"
45
+ message = "NPC зупинився через ваші сумніви."
46
+ else:
47
+ message = "Некоректний вибір. NPC очікує вашого рішення."
48
 
49
+ return game_status[current_game_status], npc_states[current_npc_state]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
  # Інтерфейс Gradio
52
+ def reset_game():
53
+ global current_game_status, current_npc_state
54
+ current_game_status = "active"
55
+ current_npc_state = "початковий"
56
+ return "active", npc_states["початковий"]
 
 
 
 
 
 
57
 
58
+ with gr.Blocks() as demo:
59
+ gr.Markdown("## NPC Familia: Духовний розвиток вашого персонажа")
60
+ current_status = gr.Textbox(label="Статус гри", value="active", interactive=False)
61
+ current_state = gr.Textbox(label="Стан NPC", value=npc_states["початковий"], interactive=False)
62
+
63
+ with gr.Row():
64
+ btn_forward = gr.Button("Крок вперед")
65
+ btn_doubt = gr.Button("Сумніви")
66
+ btn_reset = gr.Button("Почати заново")
67
+
68
+ btn_forward.click(fn=lambda: interact_with_npc("1"), inputs=[], outputs=[current_status, current_state])
69
+ btn_doubt.click(fn=lambda: interact_with_npc("2"), inputs=[], outputs=[current_status, current_state])
70
+ btn_reset.click(fn=reset_game, inputs=[], outputs=[current_status, current_state])
71
 
72
+ demo.launch()