Adieva-15 commited on
Commit
cbc0c5c
·
1 Parent(s): f2d9d5c

added chat.py

Browse files
__pycache__/config.cpython-313.pyc DELETED
Binary file (1.01 kB)
 
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import os
2
- from flask import Flask, request, render_template, send_file, jsonify
3
  import io
4
  import requests
5
  import base64
@@ -8,14 +8,12 @@ from functions import (
8
  sentiment_analysis,
9
  generate_text,
10
  summarize_text,
11
- # colorize_photo
12
  )
13
 
14
 
15
-
16
  app = Flask(__name__)
17
 
18
-
19
  UPLOAD_FOLDER = 'uploads'
20
  RESULTS_FOLDER = 'static/results'
21
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
@@ -52,6 +50,9 @@ def index():
52
  else:
53
  error = "Введите текст для пересказа"
54
 
 
 
 
55
  # # ---------- Функции с фото ----------
56
  # elif action in ['colorize']:
57
  # if 'image' not in request.files:
@@ -91,6 +92,19 @@ def index():
91
 
92
  return render_template('index.html', result_text=result_text, error=error)
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  if __name__=='__main__':
95
 
96
  app.run(debug=True, host='0.0.0.0', port=7860)
 
1
  import os
2
+ from flask import Flask, request, render_template, session, send_file, jsonify
3
  import io
4
  import requests
5
  import base64
 
8
  sentiment_analysis,
9
  generate_text,
10
  summarize_text,
11
+ chat_with_agent
12
  )
13
 
14
 
 
15
  app = Flask(__name__)
16
 
 
17
  UPLOAD_FOLDER = 'uploads'
18
  RESULTS_FOLDER = 'static/results'
19
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
 
50
  else:
51
  error = "Введите текст для пересказа"
52
 
53
+ elif action=="chat":
54
+ pass
55
+
56
  # # ---------- Функции с фото ----------
57
  # elif action in ['colorize']:
58
  # if 'image' not in request.files:
 
92
 
93
  return render_template('index.html', result_text=result_text, error=error)
94
 
95
+ @app.route('/chat', methods=['POST'])
96
+ def chat_endpoint():
97
+ """AJAX - эндпоинn для общения с ИИ - агентом."""
98
+ data = request.data.get_json()
99
+ user_message=data.get('message', '').strip()
100
+ if not user_message:
101
+ return jsonify({'error':'сообщение не молжет пустым'})
102
+
103
+ history = session.get('chat_history',[])
104
+ reply, new_history=chat_with_agent(history, user_message)
105
+ session['chat_history']=new_history
106
+ return jsonify({'reply':reply})
107
+
108
  if __name__=='__main__':
109
 
110
  app.run(debug=True, host='0.0.0.0', port=7860)
functions/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
  from functions.sentiment import sentiment_analysis
2
  from functions.generate_text import generate_text
3
  from functions.summarize import summarize_text
4
-
 
1
  from functions.sentiment import sentiment_analysis
2
  from functions.generate_text import generate_text
3
  from functions.summarize import summarize_text
4
+ from functions.chat import chat_with_agent
functions/generate_text.py CHANGED
@@ -1,4 +1,4 @@
1
- from config import model_gt
2
  import torch
3
  from transformers import GPT2Tokenizer, GPT2LMHeadModel
4
 
 
1
+ from networkbot.networkbot.config import model_gt
2
  import torch
3
  from transformers import GPT2Tokenizer, GPT2LMHeadModel
4
 
functions/sentiment.py CHANGED
@@ -1,5 +1,5 @@
1
 
2
- from config import model_name
3
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
  import torch
5
 
 
1
 
2
+ from networkbot.networkbot.config import model_name
3
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
  import torch
5
 
functions/summarize.py CHANGED
@@ -1,4 +1,4 @@
1
- from config import model_sum
2
  from transformers import AutoTokenizer, T5ForConditionalGeneration
3
  import torch
4
 
 
1
+ from networkbot.networkbot.config import model_sum
2
  from transformers import AutoTokenizer, T5ForConditionalGeneration
3
  import torch
4
 
requirements.txt CHANGED
@@ -6,4 +6,6 @@ opencv-python
6
  gunicorn #синх
7
  pillow
8
  requests
 
 
9
 
 
6
  gunicorn #синх
7
  pillow
8
  requests
9
+ openai
10
+ numpy
11
 
templates/index.html CHANGED
@@ -27,46 +27,104 @@
27
  <option value="sentiment">Анализ тональности</option>
28
  <option value="generate">Генерация текста</option>
29
  <option value="summarize">Пересказ текста</option>
30
- <!-- <option value="colorize">Раскрасить ч/б</option>-->
31
  </select>
32
  <br><br>
33
  <textarea name="text" id="textInput" rows="4" cols="50" placeholder="Введите текст..."></textarea>
34
  <br>
35
- <!-- <input type="file" name="image" accept="image/*" id="imageInput">-->
36
  <input type="submit" value="Отправить">
37
-
38
- <!-- <h3>Фото-функция</h3>-->
39
- <!-- <select name="action">-->
40
- <!-- <option value="colorize" selected>Раскрасить ч/б</option>-->
41
- <!-- </select>-->
42
- <!-- <br><br>-->
43
- <!-- <input type="file" name="image" accept="image/*" required>-->
44
- <!-- <br>-->
45
- <!-- <input type="submit" value="Отправить">-->
46
  </div>
47
  </form>
48
 
49
- <!-- <script>-->
50
- <!-- const form = document.getElementById('mainForm');-->
51
- <!-- const actionSelect = document.getElementById('actionSelect');-->
52
- <!-- const textInput = document.getElementById('textInput');-->
53
- <!-- const imageInput = document.getElementById('imageInput');-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
- <!-- form.addEventListener('submit', function(e) {-->
56
- <!-- const action = actionSelect.value;-->
57
- <!-- if (['sentiment', 'generate', 'summarize'].includes(action)) {-->
58
- <!-- if (!textInput.value.trim()) {-->
59
- <!-- e.preventDefault();-->
60
- <!-- alert('Введите текст');-->
61
- <!-- }-->
62
- <!-- } else if (['colorize',].includes(action)) {-->
63
- <!-- if (!imageInput.files.length) {-->
64
- <!-- e.preventDefault();-->
65
- <!-- alert('Выберите файл');-->
66
- <!-- }-->
67
- <!-- }-->
68
- <!-- });-->
69
- <!-- </script>-->
70
 
71
  {% if result_text %}
72
  <div class="result">
 
27
  <option value="sentiment">Анализ тональности</option>
28
  <option value="generate">Генерация текста</option>
29
  <option value="summarize">Пересказ текста</option>
30
+ <option value="chat">Чат с ИИ-агентом</option>
31
  </select>
32
  <br><br>
33
  <textarea name="text" id="textInput" rows="4" cols="50" placeholder="Введите текст..."></textarea>
34
  <br>
 
35
  <input type="submit" value="Отправить">
 
 
 
 
 
 
 
 
 
36
  </div>
37
  </form>
38
 
39
+ <script>
40
+ // Получаем историю из сессии (передана из Flask)
41
+ const initialHistory = {{ chat_history|tojson|safe }};
42
+
43
+ function addMessage(role, text) {
44
+ const container = document.getElementById('chat-messages');
45
+ const div = document.createElement('div');
46
+ div.className = 'message ' + role;
47
+ div.style.margin = '5px 0';
48
+ if (role === 'user') {
49
+ div.style.textAlign = 'right';
50
+ div.style.color = 'blue';
51
+ } else {
52
+ div.style.textAlign = 'left';
53
+ div.style.color = 'green';
54
+ }
55
+ div.textContent = text;
56
+ container.appendChild(div);
57
+ container.scrollTop = container.scrollHeight;
58
+ }
59
+
60
+ // Загружаем историю при загрузке страницы (если есть)
61
+ window.addEventListener('DOMContentLoaded', function() {
62
+ if (initialHistory) {
63
+ initialHistory.forEach(msg => {
64
+ if (msg.role !== 'system') {
65
+ addMessage(msg.role, msg.content);
66
+ }
67
+ });
68
+ }
69
+ // Показываем чат, если выбрана опция
70
+ const select = document.getElementById('actionSelect');
71
+ toggleChat(select.value);
72
+ });
73
+
74
+ // Переключение видимости чата и текстового поля
75
+ function toggleChat(action) {
76
+ const textArea = document.getElementById('text-input-area');
77
+ const chatContainer = document.getElementById('chat-container');
78
+ const submitBtn = document.getElementById('submitBtn');
79
+ if (action === 'chat') {
80
+ textArea.style.display = 'none';
81
+ chatContainer.style.display = 'block';
82
+ submitBtn.style.display = 'none'; // скрываем кнопку отправки формы
83
+ } else {
84
+ textArea.style.display = 'block';
85
+ chatContainer.style.display = 'none';
86
+ submitBtn.style.display = 'inline-block';
87
+ }
88
+ }
89
+
90
+ document.getElementById('actionSelect').addEventListener('change', function() {
91
+ toggleChat(this.value);
92
+ });
93
+
94
+ // Отправка сообщения в чате
95
+ document.getElementById('chat-send').addEventListener('click', function() {
96
+ const input = document.getElementById('chat-input');
97
+ const msg = input.value.trim();
98
+ if (!msg) return;
99
+ addMessage('user', msg);
100
+ input.value = '';
101
+ // Отправляем на сервер
102
+ fetch('/chat', {
103
+ method: 'POST',
104
+ headers: {'Content-Type': 'application/json'},
105
+ body: JSON.stringify({message: msg})
106
+ })
107
+ .then(response => response.json())
108
+ .then(data => {
109
+ if (data.reply) {
110
+ addMessage('assistant', data.reply);
111
+ } else if (data.error) {
112
+ addMessage('assistant', 'Ошибка: ' + data.error);
113
+ }
114
+ })
115
+ .catch(error => {
116
+ addMessage('assistant', 'Ошибка сети: ' + error);
117
+ });
118
+ });
119
 
120
+ // Отправка по Enter
121
+ document.getElementById('chat-input').addEventListener('keypress', function(e) {
122
+ if (e.key === 'Enter') {
123
+ document.getElementById('chat-send').click();
124
+ e.preventDefault();
125
+ }
126
+ });
127
+ </script>
 
 
 
 
 
 
 
128
 
129
  {% if result_text %}
130
  <div class="result">