Spaces:
Building
Building
File size: 10,177 Bytes
c9f9492 7fda6bb c9f9492 3b3890c e4aee44 d6f5800 96ceb67 d9915b1 08bac12 f5477de 08bac12 aa40f07 d9915b1 b27d4ac 6f04473 c050c45 96ceb67 0b28249 6f04473 0b28249 6f04473 0b28249 a9522e9 0b28249 aa40f07 0b28249 96ceb67 c050c45 c9f9492 aa40f07 c9f9492 d6f5800 0b28249 6f04473 0b28249 d6f5800 d9915b1 6f04473 a9522e9 c050c45 6f04473 c050c45 d6f5800 b27d4ac d9915b1 c050c45 b27d4ac 6f04473 a9522e9 b27d4ac a9522e9 6f04473 a9522e9 b27d4ac d6f5800 b27d4ac d6f5800 974d749 c050c45 c9f9492 d6f5800 c9f9492 96ceb67 3b3890c 96ceb67 3b3890c c9f9492 d6f5800 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
import display_gloss as dg
import synonyms_preprocess as sp
from NLP_Spacy_base_translator import NlpSpacyBaseTranslator
from flask import Flask, render_template, Response, request, send_file
import io
import cv2
import numpy as np
import os
import requests
from urllib.parse import quote, unquote
import tempfile
import re
app = Flask(__name__, static_folder='static')
app.config['TITLE'] = 'Sign Language Translate'
nlp, dict_docs_spacy = sp.load_spacy_values()
dataset, list_2000_tokens = dg.load_data()
def clean_quotes(text):
"""따옴표 정리 함수"""
# 연속된 따옴표 제거
text = re.sub(r"'+", "'", text)
# 단어 중간의 따옴표 제거
text = re.sub(r"(\w)'(\w)", r"\1\2", text)
return text
def normalize_quotes(text):
"""따옴표 형식을 정규화하는 함수"""
# 먼저 모든 따옴표를 정리
text = clean_quotes(text)
# 한글 또는 영어 단어를 찾아서 처리
pattern = r'([가-힣A-Za-z]+)'
def process_match(match):
word = match.group(1)
# 이미 따옴표로 둘러싸인 경우는 처리하지 않음
if not re.match(r"'.*'", word):
return f"'{word}'"
return word
# 단어 단위로 처리
words = text.split()
processed_words = []
for word in words:
if re.search(pattern, word):
# 이미 따옴표가 있는 경우는 그대로 두고, 없는 경우만 추가
if not word.startswith("'") and not word.endswith("'"):
word = f"'{word}'"
processed_words.append(word)
return ' '.join(processed_words)
def find_quoted_words(text):
"""작은따옴표로 묶인 단어들을 찾는 함수"""
return re.findall(r"'([^']*)'", text)
def spell_out_word(word):
"""단어를 개별 알파벳으로 분리하는 함수"""
return ' '.join(list(word.lower()))
def is_english(text):
"""텍스트가 영어인지 확인하는 함수"""
english_pattern = re.compile(r'^[A-Za-z\s\'".,!?-]+$')
return bool(english_pattern.match(text.replace("'", "")))
def translate_korean_to_english(text):
"""전체 텍스트 번역 함수"""
try:
# 입력 텍스트 정규화
text = normalize_quotes(text)
# 영어 입력 확인
if is_english(text):
return text
# 따옴표로 묶인 단어들 찾기
quoted_words = re.findall(r"'([^']*)'", text)
translated_quoted = {}
# 따옴표 안의 단어들 먼저 번역
for word in quoted_words:
if not word.strip(): # 빈 문자열 건너뛰기
continue
url = "https://translate.googleapis.com/translate_a/single"
params = {
"client": "gtx",
"sl": "ko",
"tl": "en",
"dt": "t",
"q": word
}
response = requests.get(url, params=params)
if response.status_code == 200:
translated = response.json()[0][0][0].upper()
translated_quoted[word] = translated
# 임시 마커로 대체
text = text.replace(f"'{word}'", f"QUOTED_{len(translated_quoted)}_")
# 전체 문장 번역
params = {
"client": "gtx",
"sl": "ko",
"tl": "en",
"dt": "t",
"q": text
}
response = requests.get(url, params=params)
if response.status_code == 200:
translated_text = ' '.join(item[0] for item in response.json()[0] if item[0])
# 번역된 텍스트에서 마커를 번역된 단어로 대체
for i, (original, translated) in enumerate(translated_quoted.items(), 1):
translated_text = translated_text.replace(f"QUOTED_{i}_", f"'{translated}'")
return translated_text
else:
raise Exception(f"Translation API returned status code: {response.status_code}")
except Exception as e:
print(f"Translation error: {e}")
return text
@app.route('/')
def index():
return render_template('index.html', title=app.config['TITLE'])
@app.route('/translate/', methods=['POST'])
def result():
if request.method == 'POST':
input_text = request.form['inputSentence'].strip()
if not input_text:
return render_template('error.html', error="Please enter text to translate")
try:
# 입력 텍스트 정규화
input_text = normalize_quotes(input_text)
# 번역 수행
english_text = translate_korean_to_english(input_text)
if not english_text:
raise Exception("Translation failed")
# 따옴표로 묶인 단어 추출
quoted_words = [word.strip("'") for word in re.findall(r"'([^']*)'", english_text)]
# ASL 변환을 위해 따옴표 제거
clean_english = re.sub(r"'([^']*)'", r"\1", english_text)
eng_to_asl_translator = NlpSpacyBaseTranslator(sentence=clean_english)
generated_gloss = eng_to_asl_translator.translate_to_gloss()
# 단어 처리
processed_gloss = []
words = generated_gloss.split()
for word in words:
word_upper = word.upper()
if any(quoted.upper() == word_upper for quoted in quoted_words):
# 고유명사인 경우 철자를 하나씩 분리
spelled_word = spell_out_word(word)
processed_gloss.extend(['FINGERSPELL-START'] + spelled_word.split() + ['FINGERSPELL-END'])
else:
# 일반 단어는 기존 방식대로 처리
word_lower = word.lower()
if word_lower.isalnum():
processed_gloss.append(word_lower)
gloss_sentence_before_synonym = " ".join(processed_gloss)
# 고유명사가 아닌 단어들만 동의어 처리
final_gloss = []
i = 0
while i < len(processed_gloss):
if processed_gloss[i] == 'FINGERSPELL-START':
final_gloss.extend(processed_gloss[i:i+2])
i += 2
while i < len(processed_gloss) and processed_gloss[i] != 'FINGERSPELL-END':
final_gloss.append(processed_gloss[i])
i += 1
if i < len(processed_gloss):
final_gloss.append(processed_gloss[i])
i += 1
else:
word = processed_gloss[i]
final_gloss.append(sp.find_synonyms(word, nlp, dict_docs_spacy, list_2000_tokens))
i += 1
gloss_sentence_after_synonym = " ".join(final_gloss)
return render_template('result.html',
title=app.config['TITLE'],
original_sentence=input_text,
english_translation=english_text,
gloss_sentence_before_synonym=gloss_sentence_before_synonym,
gloss_sentence_after_synonym=gloss_sentence_after_synonym)
except Exception as e:
return render_template('error.html', error=f"Translation error: {str(e)}")
def generate_complete_video(gloss_list, dataset, list_2000_tokens):
try:
frames = []
is_spelling = False
for gloss in gloss_list:
if gloss == 'FINGERSPELL-START':
is_spelling = True
continue
elif gloss == 'FINGERSPELL-END':
is_spelling = False
continue
for frame in dg.generate_video([gloss], dataset, list_2000_tokens):
frame_data = frame.split(b'\r\n\r\n')[1]
nparr = np.frombuffer(frame_data, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
frames.append(img)
if not frames:
raise Exception("No frames generated")
height, width = frames[0].shape[:2]
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_file:
temp_path = temp_file.name
out = cv2.VideoWriter(temp_path, fourcc, 25, (width, height))
for frame in frames:
out.write(frame)
out.release()
with open(temp_path, 'rb') as f:
video_bytes = f.read()
os.remove(temp_path)
return video_bytes
except Exception as e:
print(f"Error generating video: {str(e)}")
raise
@app.route('/video_feed')
def video_feed():
sentence = request.args.get('gloss_sentence_to_display', '')
gloss_list = sentence.split()
return Response(dg.generate_video(gloss_list, dataset, list_2000_tokens),
mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/download_video/<path:gloss_sentence>')
def download_video(gloss_sentence):
try:
decoded_sentence = unquote(gloss_sentence)
gloss_list = decoded_sentence.split()
if not gloss_list:
return "No gloss provided", 400
video_bytes = generate_complete_video(gloss_list, dataset, list_2000_tokens)
if not video_bytes:
return "Failed to generate video", 500
return send_file(
io.BytesIO(video_bytes),
mimetype='video/mp4',
as_attachment=True,
download_name='sign_language.mp4'
)
except Exception as e:
print(f"Download error: {str(e)}")
return f"Error downloading video: {str(e)}", 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860, debug=True) |