ginipick commited on
Commit
d9bcf7b
·
verified ·
1 Parent(s): 96f121e

Update src/main.py

Browse files
Files changed (1) hide show
  1. src/main.py +9 -60
src/main.py CHANGED
@@ -19,9 +19,7 @@ dataset, list_2000_tokens = dg.load_data()
19
 
20
  def clean_quotes(text):
21
  """따옴표 정리 함수"""
22
- # 연속된 따옴표 제거
23
  text = re.sub(r"'+", "'", text)
24
- # 불필요한 공백 제거
25
  text = re.sub(r'\s+', ' ', text).strip()
26
  return text
27
 
@@ -31,39 +29,18 @@ def is_korean(text):
31
 
32
  def is_english(text):
33
  """텍스트가 영어인지 확인하는 함수"""
34
- # 따옴표와 공백을 제외한 나머지 텍스트 확인
35
  text_without_quotes = re.sub(r"'[^']*'|\s", "", text)
36
- # 영어 알파벳과 기본 문장부호만 포함되어 있는지 확인
37
  return bool(re.match(r'^[A-Za-z.,!?-]*$', text_without_quotes))
38
 
39
  def normalize_quotes(text):
40
  """따옴표 형식을 정규화하는 함수"""
41
- # 연속된 따옴표 제거
42
  text = re.sub(r"'+", "'", text)
43
- # 불필요한 공백 제거
44
  text = re.sub(r'\s+', ' ', text).strip()
45
 
46
- # 이미 따옴표로 묶인 단어가 있는지 확인
47
- existing_quotes = re.findall(r"'([^']*)'", text)
48
- if existing_quotes:
49
- return text # 이미 따옴표가 있으면 그대로 반환
50
-
51
- # 대문자로 된 단어 찾기 (예: JOHN)
52
- uppercase_words = re.findall(r'\b[A-Z]+\b', text)
53
- if uppercase_words:
54
- # 대문자 단어에 따옴표 추가
55
- for word in uppercase_words:
56
- text = text.replace(word, f"'{word}'")
57
  return text
58
 
59
- # 위의 조건에 해당하지 않는 경우 첫 단어에 따옴표 추가
60
- words = text.split()
61
- if words:
62
- # 모든 따옴표 제거 후 첫 단어에만 따옴표 추가
63
- first_word = words[0].replace("'", "")
64
- words[0] = f"'{first_word}'"
65
- words[1:] = [w.replace("'", "") for w in words[1:]]
66
- return ' '.join(words)
67
  return text
68
 
69
  def find_quoted_words(text):
@@ -77,21 +54,19 @@ def spell_out_word(word):
77
  def translate_korean_text(text):
78
  """한글 전용 번역 함수"""
79
  try:
80
- # 1. 따옴표로 묶인 단어 찾기
81
  quoted_match = re.search(r"'([^']*)'", text)
82
  if not quoted_match:
83
  return text
84
 
85
  quoted_word = quoted_match.group(1)
86
 
87
- # 2. 전체 문장을 먼저 번역
88
  url = "https://translate.googleapis.com/translate_a/single"
89
  params = {
90
  "client": "gtx",
91
  "sl": "ko",
92
  "tl": "en",
93
  "dt": "t",
94
- "q": text.replace(f"'{quoted_word}'", "XXXXX") # 특수한 마커로 대체
95
  }
96
  response = requests.get(url, params=params)
97
  if response.status_code != 200:
@@ -99,11 +74,9 @@ def translate_korean_text(text):
99
 
100
  translated_text = ' '.join(item[0] for item in response.json()[0] if item[0])
101
 
102
- # 3. 따옴표 안의 단어 처리
103
- # 영어 단어이거나 대문자로 된 단어는 그대로 유지
104
- if re.match(r'^[A-Z]+$', quoted_word) or re.match(r'^[A-Za-z]+$', quoted_word):
105
  proper_noun = quoted_word.upper()
106
- else: # 한글 단어인 경우
107
  params["q"] = quoted_word
108
  response = requests.get(url, params=params)
109
  if response.status_code == 200:
@@ -111,14 +84,8 @@ def translate_korean_text(text):
111
  else:
112
  proper_noun = quoted_word.upper()
113
 
114
- # 4. 최종 문장 조합
115
- # XXXXX를 따옴표로 묶은 proper_noun으로 대체
116
  final_text = translated_text.replace("XXXXX", f"'{proper_noun}'")
117
-
118
- # 불필요한 대문자 변환 방지
119
  final_text = re.sub(r'\bNAME\b', 'name', final_text)
120
-
121
- # 마침표 처리
122
  final_text = final_text.replace(" .", ".")
123
 
124
  return final_text
@@ -130,19 +97,15 @@ def translate_korean_text(text):
130
  def translate_korean_to_english(text):
131
  """전체 텍스트 번역 함수"""
132
  try:
133
- # 입력 텍스트 정규화
134
  text = normalize_quotes(text)
135
 
136
- # 영어 입력 확인
137
  if is_english(text):
138
- # 기존 영어 처리 방식 유지
139
  quoted_match = re.search(r"'([^']*)'", text)
140
  if quoted_match:
141
  quoted_word = quoted_match.group(1).upper()
142
  text = re.sub(r"'[^']*'", f"'{quoted_word}'", text, 1)
143
  return text
144
 
145
- # 한글 입력인 경우 새로운 함수로 처리
146
  if is_korean(text):
147
  return translate_korean_text(text)
148
 
@@ -151,8 +114,6 @@ def translate_korean_to_english(text):
151
  print(f"Translation error: {e}")
152
  return text
153
 
154
-
155
-
156
  @app.route('/')
157
  def index():
158
  return render_template('index.html', title=app.config['TITLE'])
@@ -165,42 +126,30 @@ def result():
165
  return render_template('error.html', error="Please enter text to translate")
166
 
167
  try:
168
- # 입력 텍스트 정규화
169
  input_text = normalize_quotes(input_text)
170
-
171
- # 번역 수행
172
  english_text = translate_korean_to_english(input_text)
173
  if not english_text:
174
  raise Exception("Translation failed")
175
 
176
- # 따옴표로 묶인 단어 추출 (첫 번째 단어만)
177
- quoted_words = re.findall(r"'([^']*)'", english_text)
178
- first_quoted_word = quoted_words[0] if quoted_words else None
179
 
180
- # ASL 변환을 위해 따옴표 제거
181
  clean_english = re.sub(r"'([^']*)'", r"\1", english_text)
182
  eng_to_asl_translator = NlpSpacyBaseTranslator(sentence=clean_english)
183
  generated_gloss = eng_to_asl_translator.translate_to_gloss()
184
 
185
- # 단어 처리
186
  processed_gloss = []
187
  words = generated_gloss.split()
188
 
189
  for word in words:
190
  word_upper = word.upper()
191
- if first_quoted_word and word_upper == first_quoted_word.upper():
192
- # 고유명사인 경우 철자를 하나씩 분리
193
  spelled_word = spell_out_word(word)
194
  processed_gloss.extend(['FINGERSPELL-START'] + spelled_word.split() + ['FINGERSPELL-END'])
195
  else:
196
- # 일반 단어는 기존 방식대로 처리
197
- word_lower = word.lower()
198
- if word_lower.isalnum():
199
- processed_gloss.append(word_lower)
200
 
201
  gloss_sentence_before_synonym = " ".join(processed_gloss)
202
 
203
- # 고유명사가 아닌 단어들만 동의어 처리
204
  final_gloss = []
205
  i = 0
206
  while i < len(processed_gloss):
@@ -304,4 +253,4 @@ def download_video(gloss_sentence):
304
  return f"Error downloading video: {str(e)}", 500
305
 
306
  if __name__ == "__main__":
307
- app.run(host="0.0.0.0", port=7860, debug=True)
 
19
 
20
  def clean_quotes(text):
21
  """따옴표 정리 함수"""
 
22
  text = re.sub(r"'+", "'", text)
 
23
  text = re.sub(r'\s+', ' ', text).strip()
24
  return text
25
 
 
29
 
30
  def is_english(text):
31
  """텍스트가 영어인지 확인하는 함수"""
 
32
  text_without_quotes = re.sub(r"'[^']*'|\s", "", text)
 
33
  return bool(re.match(r'^[A-Za-z.,!?-]*$', text_without_quotes))
34
 
35
  def normalize_quotes(text):
36
  """따옴표 형식을 정규화하는 함수"""
 
37
  text = re.sub(r"'+", "'", text)
 
38
  text = re.sub(r'\s+', ' ', text).strip()
39
 
40
+ # 이미 따옴표로 묶인 단어가 있으면 그대로 반환
41
+ if re.search(r"'[^']*'", text):
 
 
 
 
 
 
 
 
 
42
  return text
43
 
 
 
 
 
 
 
 
 
44
  return text
45
 
46
  def find_quoted_words(text):
 
54
  def translate_korean_text(text):
55
  """한글 전용 번역 함수"""
56
  try:
 
57
  quoted_match = re.search(r"'([^']*)'", text)
58
  if not quoted_match:
59
  return text
60
 
61
  quoted_word = quoted_match.group(1)
62
 
 
63
  url = "https://translate.googleapis.com/translate_a/single"
64
  params = {
65
  "client": "gtx",
66
  "sl": "ko",
67
  "tl": "en",
68
  "dt": "t",
69
+ "q": text.replace(f"'{quoted_word}'", "XXXXX")
70
  }
71
  response = requests.get(url, params=params)
72
  if response.status_code != 200:
 
74
 
75
  translated_text = ' '.join(item[0] for item in response.json()[0] if item[0])
76
 
77
+ if re.match(r'^[A-Za-z]+$', quoted_word):
 
 
78
  proper_noun = quoted_word.upper()
79
+ else:
80
  params["q"] = quoted_word
81
  response = requests.get(url, params=params)
82
  if response.status_code == 200:
 
84
  else:
85
  proper_noun = quoted_word.upper()
86
 
 
 
87
  final_text = translated_text.replace("XXXXX", f"'{proper_noun}'")
 
 
88
  final_text = re.sub(r'\bNAME\b', 'name', final_text)
 
 
89
  final_text = final_text.replace(" .", ".")
90
 
91
  return final_text
 
97
  def translate_korean_to_english(text):
98
  """전체 텍스트 번역 함수"""
99
  try:
 
100
  text = normalize_quotes(text)
101
 
 
102
  if is_english(text):
 
103
  quoted_match = re.search(r"'([^']*)'", text)
104
  if quoted_match:
105
  quoted_word = quoted_match.group(1).upper()
106
  text = re.sub(r"'[^']*'", f"'{quoted_word}'", text, 1)
107
  return text
108
 
 
109
  if is_korean(text):
110
  return translate_korean_text(text)
111
 
 
114
  print(f"Translation error: {e}")
115
  return text
116
 
 
 
117
  @app.route('/')
118
  def index():
119
  return render_template('index.html', title=app.config['TITLE'])
 
126
  return render_template('error.html', error="Please enter text to translate")
127
 
128
  try:
 
129
  input_text = normalize_quotes(input_text)
 
 
130
  english_text = translate_korean_to_english(input_text)
131
  if not english_text:
132
  raise Exception("Translation failed")
133
 
134
+ quoted_words = find_quoted_words(english_text)
 
 
135
 
 
136
  clean_english = re.sub(r"'([^']*)'", r"\1", english_text)
137
  eng_to_asl_translator = NlpSpacyBaseTranslator(sentence=clean_english)
138
  generated_gloss = eng_to_asl_translator.translate_to_gloss()
139
 
 
140
  processed_gloss = []
141
  words = generated_gloss.split()
142
 
143
  for word in words:
144
  word_upper = word.upper()
145
+ if quoted_words and word_upper in [w.upper() for w in quoted_words]:
 
146
  spelled_word = spell_out_word(word)
147
  processed_gloss.extend(['FINGERSPELL-START'] + spelled_word.split() + ['FINGERSPELL-END'])
148
  else:
149
+ processed_gloss.append(word.lower())
 
 
 
150
 
151
  gloss_sentence_before_synonym = " ".join(processed_gloss)
152
 
 
153
  final_gloss = []
154
  i = 0
155
  while i < len(processed_gloss):
 
253
  return f"Error downloading video: {str(e)}", 500
254
 
255
  if __name__ == "__main__":
256
+ app.run(host="0.0.0.0", port=7860, debug=True)