bvd757 commited on
Commit
c4528c6
·
1 Parent(s): 9c24cef

with_chat_gpt_now

Browse files
Files changed (2) hide show
  1. app.py +2 -60
  2. search_errors_logic.py +105 -17
app.py CHANGED
@@ -2,7 +2,7 @@ import language_tool_python
2
  import openai
3
  import streamlit as st
4
  import subprocess
5
- from search_errors_logic import check_text
6
  import html
7
  import docx
8
  from io import BytesIO
@@ -73,64 +73,6 @@ def load_assets():
73
  return tool
74
 
75
 
76
- # def generate_gpt_comment_openai(inp):
77
- # response = openai.ChatCompletion.create(
78
- # model="gpt-4o-mini",
79
- # messages=[
80
- # {"role": "user", "content": inp}
81
- # ]
82
- # )
83
- # return response.choices[0].message['content']
84
-
85
-
86
- # def generate_gpt_comment_vsegpt(inp):
87
- # client = openai.OpenAI(
88
- # api_key='sk-or-vv-44ca318747a45e810149bf769e9dfbe5f42046695875efd7c9121cca590d6906',
89
- # base_url='https://api.vsegpt.ru/v1',
90
- # )
91
- # response = client.chat.completions.create(
92
- # model="gpt-4o-mini",
93
- # messages=[{"role": "user", "content": inp}]
94
- # ).choices[0].message.content
95
-
96
- # return response
97
-
98
-
99
- # def generate_gpt_comment(inp, client_name):
100
- # if client_name == "openai":
101
- # return generate_gpt_comment_openai(inp)
102
- # elif client_name == "vsegpt":
103
- # return generate_gpt_comment_vsegpt(inp)
104
- # else:
105
- # raise ValueError(f"Unsupported client: {client_name}")
106
-
107
-
108
- # def check_text(text, tool):
109
- # matches = tool.check(text)
110
- # errors = []
111
- # for match in matches:
112
- # inp = prompt.format(text[match.offset:match.offset + match.errorLength],
113
- # match.message, match.context)
114
- # error_info = {
115
- # 'start': match.offset,
116
- # 'end': match.offset + match.errorLength,
117
- # 'message': generate_gpt_comment(inp, client_name="vsegpt"),
118
- # }
119
- # errors.append(error_info)
120
-
121
- # errors = sorted(errors, key=lambda x: x['end'])
122
-
123
- # shift = 0
124
- # for i, error in enumerate(errors, 1):
125
- # error['start'] += shift
126
- # error['end'] += shift
127
- # inp = f"({i})"
128
- # text = text[:error['end']] + inp + text[error['end']:]
129
- # shift += len(inp)
130
-
131
- # return text.replace("\n", " "), errors
132
-
133
-
134
  def extract_text_from_docx(file):
135
  doc = docx.Document(BytesIO(file.getvalue()))
136
  full_text = []
@@ -194,7 +136,7 @@ def main():
194
  if not text.strip():
195
  st.warning("Введите текст для проверки")
196
  else:
197
- text, errors = check_text(text, tool)
198
  if not errors:
199
  st.success("Ошибок не найдено! 👍")
200
  else:
 
2
  import openai
3
  import streamlit as st
4
  import subprocess
5
+ from checked.search_errors_logic import check_text, check_text_chat_gpt
6
  import html
7
  import docx
8
  from io import BytesIO
 
73
  return tool
74
 
75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  def extract_text_from_docx(file):
77
  doc = docx.Document(BytesIO(file.getvalue()))
78
  full_text = []
 
136
  if not text.strip():
137
  st.warning("Введите текст для проверки")
138
  else:
139
+ text, errors = check_text_chat_gpt(text, tool)
140
  if not errors:
141
  st.success("Ошибок не найдено! 👍")
142
  else:
search_errors_logic.py CHANGED
@@ -1,6 +1,44 @@
1
  import openai
2
  from openai import OpenAI
 
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  prompt = """
6
  Ты должен писать комментарии об ошибках в тексте.
@@ -45,7 +83,7 @@ prompt = """
45
  """
46
 
47
 
48
- def generate_gpt_comment_openai(inp):
49
  response = openai.ChatCompletion.create(
50
  model="gpt-4o-mini",
51
  messages=[
@@ -55,7 +93,7 @@ def generate_gpt_comment_openai(inp):
55
  return response.choices[0].message['content']
56
 
57
 
58
- def generate_gpt_comment_vsegpt(inp):
59
  client = OpenAI(
60
  api_key='sk-or-vv-44ca318747a45e810149bf769e9dfbe5f42046695875efd7c9121cca590d6906',
61
  base_url='https://api.vsegpt.ru/v1'
@@ -68,15 +106,74 @@ def generate_gpt_comment_vsegpt(inp):
68
  return response
69
 
70
 
71
- def generate_gpt_comment(inp, client_name):
72
  if client_name == "openai":
73
- return generate_gpt_comment_openai(inp)
74
  elif client_name == "vsegpt":
75
- return generate_gpt_comment_vsegpt(inp)
76
  else:
77
  raise ValueError(f"Unsupported client: {client_name}")
78
 
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  def check_text(text, tool):
81
  matches = tool.check(text)
82
  errors = []
@@ -86,18 +183,9 @@ def check_text(text, tool):
86
  error_info = {
87
  'start': match.offset,
88
  'end': match.offset + match.errorLength,
89
- 'message': generate_gpt_comment(inp, client_name="vsegpt"),
90
  }
91
  errors.append(error_info)
92
 
93
- errors = sorted(errors, key=lambda x: x['end'])
94
-
95
- shift = 0
96
- for i, error in enumerate(errors, 1):
97
- error['start'] += shift
98
- error['end'] += shift
99
- inp = f"({i})"
100
- text = text[:error['end']] + inp + text[error['end']:]
101
- shift += len(inp)
102
-
103
- return text.replace("\n", " "), errors
 
1
  import openai
2
  from openai import OpenAI
3
+ import difflib
4
 
5
+ prompt_fix_text_gpt = "Исправь ошибки в данном тексте:\n{}"
6
+
7
+ prompt_compare_get_comment = """
8
+ Ты должен писать комментарии об ошибках в тексте.
9
+ Тебе дан кусок текст, в котором есть одна или несколько ошибок и этот же кусок текста с исправленными ошибками.
10
+ Твоя задача - кратко описать суть каждой ошибки и, если необходимо, исправить её. Отвечай на русском языке.
11
+
12
+
13
+ ### Пример 1:
14
+ original text:
15
+ "кросивую"
16
+
17
+ corrected text:
18
+ "красивую"
19
+
20
+ Твой ответ:
21
+ Орфографическая ошибка: "кросивую" -> "красивую".
22
+
23
+
24
+ ### Пример 2:
25
+ original:
26
+ "я решил пойти в"
27
+
28
+ corrected text:
29
+ "я решил пойти в"
30
+
31
+ Твой ответ:
32
+ Опечатка: повтор пробла.
33
+
34
+
35
+ Теперь твоя очередь:
36
+ original:
37
+ "{}"
38
+
39
+ corrected text:
40
+ "{}"
41
+ """
42
 
43
  prompt = """
44
  Ты должен писать комментарии об ошибках в тексте.
 
83
  """
84
 
85
 
86
+ def get_gpt_response_openai(inp):
87
  response = openai.ChatCompletion.create(
88
  model="gpt-4o-mini",
89
  messages=[
 
93
  return response.choices[0].message['content']
94
 
95
 
96
+ def get_gpt_response_vsegpt(inp):
97
  client = OpenAI(
98
  api_key='sk-or-vv-44ca318747a45e810149bf769e9dfbe5f42046695875efd7c9121cca590d6906',
99
  base_url='https://api.vsegpt.ru/v1'
 
106
  return response
107
 
108
 
109
+ def get_gpt_response(inp, client_name):
110
  if client_name == "openai":
111
+ return get_gpt_response_openai(inp)
112
  elif client_name == "vsegpt":
113
+ return get_gpt_response_vsegpt(inp)
114
  else:
115
  raise ValueError(f"Unsupported client: {client_name}")
116
 
117
 
118
+ def find_corrected_positions(original, corrected):
119
+ matcher = difflib.SequenceMatcher(None, original, corrected)
120
+ changes = []
121
+
122
+ for opcode in matcher.get_opcodes():
123
+ tag, i1, i2, j1, j2 = opcode
124
+ if tag != 'equal':
125
+ changes.append({
126
+ 'original': (i1, i2),
127
+ 'corrected': (j1, j2),
128
+ 'operation': tag
129
+ })
130
+
131
+ return changes
132
+
133
+
134
+ def get_piece_of_text_bounds(s, start, end):
135
+ if start != 0: start -= 1
136
+ while start != 0 and s[start] not in [' ', "\n", '\t']:
137
+ start -= 1
138
+ start += 1
139
+
140
+ if end < len(s) - 1: end += 1
141
+ while end < len(s) - 1 and s[end] not in [' ', "\n", '\t']:
142
+ end += 1
143
+ return start, end
144
+
145
+
146
+ def add_comments_to_text(text, errors):
147
+ errors = sorted(errors, key=lambda x: x['end'])
148
+
149
+ shift = 0
150
+ for i, error in enumerate(errors, 1):
151
+ error['start'] += shift
152
+ error['end'] += shift
153
+ inp = f"({i})"
154
+ text = text[:error['end']] + inp + text[error['end']:]
155
+ shift += len(inp)
156
+
157
+ return text.replace("\n", " ")
158
+
159
+
160
+ def check_text_chat_gpt(text, *args, **kwargs):
161
+ fixed_text = get_gpt_response(prompt_fix_text_gpt.format(text), "vsegpt")
162
+ changes = find_corrected_positions(text, fixed_text)
163
+ errors = []
164
+ for change in changes:
165
+ start_orig, end_orid = get_piece_of_text_bounds(text, change['original'][0], change['original'][1])
166
+ start_corr, end_corr = get_piece_of_text_bounds(fixed_text, change['corrected'][0], change['corrected'][1])
167
+ inp = prompt_compare_get_comment.format(text[start_orig:end_orid], fixed_text[start_corr:end_corr])
168
+ errors.append({
169
+ 'start': start_orig,
170
+ 'end': end_orid,
171
+ 'message': get_gpt_response(inp, client_name="vsegpt"),
172
+ })
173
+
174
+ text_with_comments = add_comments_to_text(text, errors)
175
+ return text_with_comments, errors
176
+
177
  def check_text(text, tool):
178
  matches = tool.check(text)
179
  errors = []
 
183
  error_info = {
184
  'start': match.offset,
185
  'end': match.offset + match.errorLength,
186
+ 'message': get_gpt_response(inp, client_name="vsegpt"),
187
  }
188
  errors.append(error_info)
189
 
190
+ text_with_comments = add_comments_to_text(text, errors)
191
+ return text_with_comments, errors