다음의 app.py 파일을 바탕으로 대략 다음과 같은 개념의 앱으로 새롭게 만들어주세요. Extract Parts from Your Upload File 1.…
- User
다음의 app.py 파일을 바탕으로 대략 다음과 같은 개념의 앱으로 새롭게 만들어주세요.
Extract Parts from Your Upload File
- 파일을 업로드한 후, 추출된 파일을 다운로드하는 방식
- 사용자가 시작부분과 끝부분을 입력하는 방식(기본 설정은 from "")
- 같은 부분이 여럿 또는 무수히 많을 경우에 어떻게 처리: 무효, 또는 모두, 또는 n번째, ...
========== 허깅페이스에 만들어본 extract_html_from_mht 앱의 app.py 내용 (with help by various AI of OpenAI) ==========
import gradio as gr import re import tempfile
def extract_html_from_mht(mht_content, choice="<html lang=", occurrence='1'): # 정규 표현식을 통해 모두 HTML 문서 추출 if choice == "<html": pattern = r'<html.?' elif choice == "<html lang=": pattern = r'<html lang=".?".*?' else: return ("Invalid choice.", None)
matches = re.finditer(pattern, mht_content, re.DOTALL) # 모든 매치 저장 matches_list = list(matches) if matches_list: # occurrence에 기반하여 특정 HTML 문서 선택 try: index = int(occurrence) - 1 if index >= 0 and index < len(matches_list): html_content = matches_list[index].group(0) else: return ("Invalid occurrence number.", None) except ValueError: return ("Occurrence must be a number.", None) # 임시 파일 생성 with tempfile.NamedTemporaryFile(delete=False, suffix=".html") as temp_file: temp_file.write(html_content.encode('utf-8')) temp_file_path = temp_file.name # 임시 파일의 경로 반환 return temp_file_path else: # HTML 문서가 없으면 에러 메시지 반환 return ("No valid HTML content found in the MHT file.", None)with gr.Blocks() as block: gr.Markdown("This App lets you choose the HTML tag pattern to extract from MHT content.")
mht_input = gr.Textbox(label="Paste your MHT content here", lines=20, placeholder="MHT 파일의 내용을 여기에 붙여넣기") choice_dropdown = gr.Dropdown(label="Choose HTML start pattern", choices=["<!DOCTYPE html><html", "<!DOCTYPE html><html lang="]) occurrence_input = gr.Textbox(label="Enter which occurrence to extract (number)", value="1") convert_button = gr.Button("Extract HTML from MHT") download_output = gr.File(label="Download HTML File") convert_button.click(fn=extract_html_from_mht, inputs=[mht_input, choice_dropdown, occurrence_input], outputs=download_output)block.launch()
- Assistant
아래는 사용자가 업로드한 파일에서 특정 부분을 추출하고 다운로드할 수 있는 새로운
app.py파일입니다. 이 앱은 다음과 같은 기능을 제공합니다:- 파일 업로드 및 다운로드: 사용자가 파일을 업로드한 후, 추출된 내용을 파일로 다운로드할 수 있습니다.
- 추출 패턴 입력: 사용자가 시작 부분과 끝 부분의 패턴을 입력할 수 있으며, 기본값으로
<!DOCTYPE html...부터</html>까지 설정되어 있습니다. - 다중 매치 처리 방법 선택: 동일한 패턴이 여러 번 나타나는 경우, 사용자는 다음 중 하나를 선택할 수 있습니다:
- 모두 추출: 모든 매치를 추출하여 하나의 파일로 제공합니다.
- 특정 번째 추출: 사용자가 지정한 순서의 매치만 추출합니다.
- 무효 처리: 여러 매치가 있을 경우 오류 메시지를 반환합니다.
다음은 위의 기능을 구현한
app.py코드입니다:import gradio as gr import re import tempfile def extract_parts(file, start_pattern, end_pattern, mode, occurrence=None): if file is None: return "파일이 업로드되지 않았습니다.", None try: # 파일 내용을 읽어오기 file_content = file.read().decode('utf-8') except UnicodeDecodeError: return "파일을 UTF-8 형식으로 디코딩할 수 없습니다.", None # 정규 표현식 패턴 생성 # re.escape를 사용하여 사용자가 입력한 패턴의 특수문자를 이스케이프 처리 pattern = re.escape(start_pattern) + r'(.*?)' + re.escape(end_pattern) matches = re.finditer(pattern, file_content, re.DOTALL) matches_list = [match.group(0) for match in matches] if not matches_list: return "지정한 패턴에 맞는 내용이 파일에서 발견되지 않았습니다.", None if mode == "모두 추출": extracted_content = "\n\n".join(matches_list) elif mode == "특정 번째 추출": if occurrence is None: return "추출할 occurrence을 입력해주세요.", None try: index = int(occurrence) - 1 if index < 0 or index >= len(matches_list): return f"입력한 occurrence({occurrence})가 범위를 벗어났습니다. 총 {len(matches_list)}개의 매치가 있습니다.", None extracted_content = matches_list[index] except ValueError: return "Occurrence은 숫자여야 합니다.", None elif mode == "무효 처리": if len(matches_list) > 1: return f"패턴이 여러 번 발견되었습니다 ({len(matches_list)}회). 무효로 처리됩니다.", None extracted_content = matches_list[0] else: return "유효하지 않은 처리 모드입니다.", None # 임시 파일 생성 및 내용 쓰기 with tempfile.NamedTemporaryFile(delete=False, suffix=".txt") as temp_file: temp_file.write(extracted_content.encode('utf-8')) temp_file_path = temp_file.name return None, temp_file_path with gr.Blocks() as demo: gr.Markdown("# 파일에서 특정 부분 추출 및 다운로드") with gr.Row(): with gr.Column(): file_input = gr.File(label="파일 업로드", file_types=["text", "html", "mht"], type="file") start_input = gr.Textbox( label="시작 패턴", value="<!DOCTYPE html>", placeholder="시작 부분을 지정하세요 (예: <!DOCTYPE html>)" ) end_input = gr.Textbox( label="끝 패턴", value="</html>", placeholder="끝 부분을 지정하세요 (예: </html>)" ) mode_dropdown = gr.Dropdown( label="매치 처리 방식", choices=["무효 처리", "모두 추출", "특정 번째 추출"], value="무효 처리" ) occurrence_input = gr.Textbox( label="추출할 Occurrence 번호 (mode가 '특정 번째 추출'일 때)", placeholder="예: 1", visible=False ) extract_button = gr.Button("부분 추출 및 다운로드") with gr.Column(): output_message = gr.Markdown("") download_output = gr.File(label="추출된 파일 다운로드") def toggle_occurrence_visibility(mode): return gr.update(visible=(mode == "특정 번째 추출")) mode_dropdown.change(toggle_occurrence_visibility, inputs=mode_dropdown, outputs=occurrence_input) extract_button.click( fn=extract_parts, inputs=[file_input, start_input, end_input, mode_dropdown, occurrence_input], outputs=[output_message, download_output] ) demo.launch()코드 설명
-
라이브러리 임포트:
gradio: 사용자 인터페이스를 생성하기 위해 사용됩니다.re: 정규 표현식을 사용하여 패턴을 매칭합니다.tempfile: 임시 파일을 생성하여 추출된 내용을 저장하고 다운로드할 수 있게 합니다.
-
extract_parts함수:- 입력:
file: 사용자가 업로드한 파일.start_pattern: 추출할 시작 패턴.end_pattern: 추출할 끝 패턴.mode: 매치 처리 방식 (무효 처리,모두 추출,특정 번째 추출중 선택).occurrence: 특정 번째 매치를 추출할 때 사용할 번호.
- 동작:
- 파일 내용을 UTF-8로 디코딩합니다.
- 사용자가 입력한 시작 및 끝 패턴을 사용하여 정규 표현식 패턴을 생성합니다.
- 패턴에 맞는 모든 매치를 리스트로 수집합니다.
- 선택한
mode에 따라 추출할 내용을 결정합니다.- 모두 추출: 모든 매치를 하나의 문자열로 결합.
- 특정 번째 추출: 사용자가 입력한
occurrence번호에 해당하는 매치만 추출. - 무효 처리: 매치가 여러 개인 경우 오류 메시지 반환.
- 추출된 내용을 임시 파일로 저장하고, 해당 파일의 경로를 반환합니다.
- 출력:
- 에러 메시지 (있을 경우).
- 추출된 파일의 경로.
- 입력:
-
Gradio 인터페이스 구성:
- 파일 업로드: 텍스트, HTML, MHT 파일 형식을 지원합니다.
- 시작 및 끝 패턴 입력: 기본값으로 HTML 문서 추출을 위한 패턴이 설정되어 있습니다.
- 매치 처리 방식 선택: 드롭다운 메뉴를 통해 처리 방식을 선택합니다.
- Occurrence 입력:
특정 번째 추출을 선택한 경우에만 표시되어, 사용자가 추출할 매치 번호를 입력할 수 있습니다. - 추출 버튼: 사용자가 설정한 옵션에 따라 파일에서 원하는 부분을 추출합니다.
- 결과 표시: 추출된 파일을 다운로드할 수 있는 링크를 제공합니다.
-
동적 UI 업데이트:
특정 번째 추출을 선택한 경우에만Occurrence입력 상자가 표시되도록 설정했습니다.
사용 방법
- 파일 업로드: "파일 업로드" 버튼을 클릭하여 원하는 파일을 업로드합니다.
- 시작 및 끝 패턴 설정: 기본값으로 HTML 문서를 추출하도록 설정되어 있지만, 필요에 따라 변경할 수 있습니다.
- 매치 처리 방식 선택:
- 무효 처리: 매치가 여러 개인 경우 오류 메시지를 반환합니다.
- 모두 추출: 모든 매치를 하나의 파일로 추출합니다.
- 특정 번째 추출: 특정 순서의 매치만 추출하며, 추출할 번호를 입력해야 합니다.
- 추출 및 다운로드: "부분 추출 및 다운로드" 버튼을 클릭하면 추출된 내용을 포함한 파일을 다운로드할 수 있습니다.
이 앱을 통해 다양한 파일에서 원하는 부분을 손쉽게 추출하고 사용할 수 있습니다. 필요한 경우 정규 표현식을 조정하여 보다 정교한 패턴 매칭도 가능합니다.