Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import os | |
| import json | |
| import logging | |
| from main import main as process_file_main | |
| LOG_FILE = "ocv_parser_log.txt" | |
| def process_and_download(excel_file, headers_scan_rows, window_size, column_match_threshold): | |
| """ | |
| Обрабатывает загруженный Excel-файл, генерирует JSON и возвращает файлы для скачивания. | |
| """ | |
| if excel_file is None: | |
| return None, None, "Please upload an Excel file.", None | |
| # Логгер будет настроен внутри process_file_main | |
| logger = logging.getLogger(__name__) | |
| try: | |
| input_filepath = excel_file.name | |
| output_folder = "output" | |
| # Вызываем основную функцию обработки | |
| process_file_main( | |
| input_file=input_filepath, | |
| output_folder=output_folder, | |
| debug=True, | |
| headers_scan_rows=int(headers_scan_rows), | |
| window_size=int(window_size), | |
| column_match_threshold=float(column_match_threshold), | |
| log_file=LOG_FILE, | |
| clear_log=True # Очищаем лог для каждого нового запуска | |
| ) | |
| # Определяем путь к выходному файлу, который был создан в main | |
| input_filename = os.path.basename(input_filepath) | |
| output_filename = os.path.splitext(input_filename)[0] + '.json' | |
| output_json_path = os.path.join(output_folder, output_filename) | |
| # Читаем содержимое JSON файла для отображения | |
| with open(output_json_path, 'r', encoding='utf-8') as f: | |
| json_content = json.load(f) | |
| # Форматируем JSON для красивого отображения | |
| formatted_json = json.dumps(json_content, ensure_ascii=False, indent=2) | |
| # Логируем успешное завершение | |
| logging.getLogger(__name__).info(f"Processing successful! JSON at {output_json_path}, Log at {LOG_FILE}") | |
| return output_json_path, LOG_FILE, "Processing successful!", formatted_json | |
| except Exception as e: | |
| # Логируем ошибку | |
| logging.getLogger(__name__).error(f"An error occurred in Gradio app: {e}", exc_info=True) | |
| # Возвращаем файл лога даже в случае ошибки | |
| return None, LOG_FILE, f"An error occurred: {e}", None | |
| # Описание для интерфейса Gradio | |
| description = """ | |
| # OCV Parser | |
| Upload your Excel file (Оборотно-сальдовая ведомость), adjust the parsing parameters, and get the structured JSON data. | |
| The parsed data will be shown below and also available for download. | |
| """ | |
| with gr.Blocks() as demo: | |
| gr.Markdown(description) | |
| with gr.Row(): | |
| with gr.Column(): | |
| # Входные данные | |
| excel_upload = gr.File(label="Upload Excel File", file_types=[".xlsx", ".xls"]) | |
| gr.Markdown("## Parsing Parameters") | |
| headers_scan_rows_input = gr.Slider(minimum=1, maximum=50, value=15, step=1, label="Headers Scan Rows") | |
| window_size_input = gr.Slider(minimum=10, maximum=500, value=100, step=10, label="Window Size") | |
| column_match_threshold_input = gr.Slider(minimum=0.01, maximum=1.0, value=0.05, step=0.01, label="Column Match Threshold") | |
| submit_button = gr.Button("Process File", variant="primary") | |
| with gr.Column(): | |
| # Выходные данные | |
| status_output = gr.Textbox(label="Status", interactive=False) | |
| json_output_file = gr.File(label="Download JSON Result") | |
| log_output_file = gr.File(label="Download Log File") | |
| # JSON viewer в отдельной секции под основным интерфейсом | |
| with gr.Row(): | |
| json_viewer = gr.Code( | |
| label="Parsed JSON Result", | |
| language="json", | |
| interactive=False, | |
| lines=20, # Показывать 20 строк изначально | |
| elem_classes=["json-viewer"] # Для возможной кастомизации стилей | |
| ) | |
| submit_button.click( | |
| fn=process_and_download, | |
| inputs=[ | |
| excel_upload, | |
| headers_scan_rows_input, | |
| window_size_input, | |
| column_match_threshold_input | |
| ], | |
| outputs=[ | |
| json_output_file, | |
| log_output_file, | |
| status_output, | |
| json_viewer | |
| ] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |