SPARC64 commited on
Commit
977ee64
·
verified ·
1 Parent(s): 2ba8d2f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -53
app.py CHANGED
@@ -2,55 +2,60 @@ import gradio as gr
2
  import re
3
  import os
4
  import base64
 
5
  from datetime import datetime, timedelta, timezone
6
 
7
  # 設定
8
- SUPPORT_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/main/README.md"#Githubのメインページ
9
- HELP_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/Q%26A/README.md"#GithubのFAQ
10
- COPYRIGHT_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/copyright/README.md"#Githubのコピーライトページ
11
- CONTACT_URL = "https://forms.gle/mAUj1CdhufHFbiWs7"#Googleフォーム
12
- TS_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/troubleshooting/README.md"#Githubのトラブルシューティングページ(TS=トラブルシューティング)
13
  JST = timezone(timedelta(hours=9))
14
 
15
- def load_log_file(file):
16
- """アップロードされたログファイルを開き、内容を取得"""
17
  if not file:
18
  return None, "エラー(FILE-001): ファイルが選択されていません"
19
 
20
- # ファイルの拡張子をチェック (.txt 以外はエラー)
21
  if not file.name.endswith(".txt"):
22
  return None, "エラー(FILE-005): サポートされていないファイル形式です。TXTファイルを選択してください。"
23
-
24
  try:
25
  with open(file.name, "r", encoding="utf-8") as f:
26
- content = f.readlines()
27
- return content, None
 
 
 
 
 
28
  except Exception as e:
29
  return None, "エラー(FILE-004): ファイルのエンコード形式が不正です(UTF-8のみ対応)"
30
 
31
- def search_logs(file, keyword, year, month, day):
32
- """ログを検索し、結果を返す"""
33
  log_lines, error = load_log_file(file)
34
  if error:
35
- return "", "エラー(FILE-002): ファイルの読み込みに失敗しました", None
36
 
37
  if not log_lines:
38
  return "", "エラー(FILE-003): ファイルが空です。", None
39
 
40
- # 検索条件のチェック
41
  is_word_search = bool(keyword.strip())
42
  is_date_search = year != "----" and month != "----" and day != "----"
43
 
44
  if is_word_search and is_date_search:
45
  return "", "エラー(SEARCH-001): ワード検索と日付検索は同時に行えません。", None
46
 
47
- # 検索条件の設定
48
  search_condition = "検索条件: なし"
49
  results = []
50
 
51
  if is_word_search:
52
  search_condition = f"検索条件: ワード[{keyword}]"
53
- results = [f"- {line.strip()}" for line in log_lines if keyword in line]
 
 
54
 
55
  elif is_date_search:
56
  try:
@@ -64,39 +69,16 @@ def search_logs(file, keyword, year, month, day):
64
  return "", "エラー(SEARCH-002): 無効な日付形式です。", None
65
 
66
  formatted_results = "\n".join(results) if results else "SEARCH-003: 一致する結果が見つかりませんでした。"
67
-
68
  return formatted_results, f"{len(results)} 件の結果が見つかりました。", search_condition
69
 
70
- def extract_date_range_logs(lines, start_date, end_date):
71
- """指定された日付範囲のログを抽出する"""
72
- results = []
73
- current_date = None
74
-
75
- for line in lines:
76
- date_match = re.match(r"(\d{4}/\d{1,2}/\d{1,2})", line)
77
- if date_match:
78
- try:
79
- current_date = datetime.strptime(date_match.group(1), "%Y/%m/%d")
80
- except ValueError:
81
- continue
82
-
83
- if current_date and start_date <= current_date < end_date:
84
- results.append(line.strip())
85
-
86
- return results
87
-
88
- def generate_download_link(results, search_condition):
89
- """検索結果をTXTファイルとしてbase64エンコードし、ダウンロードリンクを生成"""
90
  if not results:
91
  return "エラー(EXPORT-001): エクスポートするデータがありません。"
92
 
93
- #エクスポートファイル名に挿入する用
94
  execution_time = datetime.now(JST).strftime("%Y%m%d_%H%M%S")
95
-
96
- #エクスポートファイル内の検索実行日に表記する用
97
  JPN_date = datetime.now(JST).strftime("%Y/%m/%d %H:%M:%S")
98
-
99
- # 検索条件をファイル名に適用
100
  if "ワード" in search_condition:
101
  condition_text = search_condition.replace("検索条件: ワード[", "").replace("]", "").replace(" ", "_")
102
  elif "日付" in search_condition:
@@ -116,13 +98,13 @@ def generate_download_link(results, search_condition):
116
  )
117
 
118
  encoded_file = base64.b64encode(file_content.encode()).decode()
119
- href = f'<a href="data:text/plain;base64,{encoded_file}" download="{file_name}">結果をダウンロード</a>'
120
- return href
121
 
122
- if not encoded_file:
123
- return "エラー(EXPORT-002): エクスポートファイルの作成に失敗しました"
 
124
 
125
-
 
126
 
127
  # Gradio UI
128
  with gr.Blocks() as demo:
@@ -130,10 +112,8 @@ with gr.Blocks() as demo:
130
 
131
  file_input = gr.File(label="ログファイルをアップロード")
132
 
133
- # ユーザー検索用テキストボックス
134
  search_word = gr.Textbox(label="ユーザー検索ワード")
135
 
136
- # 日付検索用ドロップダウン
137
  year = gr.Dropdown(choices=["----"] + [str(y) for y in range(2020, 2041)], value="----", label="年")
138
  month = gr.Dropdown(choices=["----"] + [str(m) for m in range(1, 13)], value="----", label="月")
139
  day = gr.Dropdown(choices=["----"] + [str(d) for d in range(1, 32)], value="----", label="日")
@@ -144,9 +124,8 @@ with gr.Blocks() as demo:
144
 
145
  search_condition_state = gr.State()
146
 
147
- # エクスポート機能
148
  export_button = gr.Button("TXTをエクスポートする")
149
- export_output = gr.HTML() # base64エンコードしたリンクを表示
150
  export_status = gr.Textbox(label="エクスポートメッセージ", interactive=False)
151
 
152
  search_button.click(
@@ -167,5 +146,4 @@ with gr.Blocks() as demo:
167
  gr.Markdown(f"[🛠 サポート]({SUPPORT_URL})")
168
  gr.Markdown(f"[© コピーライト]({COPYRIGHT_URL})")
169
 
170
- # アプリを実行
171
  demo.launch()
 
2
  import re
3
  import os
4
  import base64
5
+ import time # 進捗バー用
6
  from datetime import datetime, timedelta, timezone
7
 
8
  # 設定
9
+ SUPPORT_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/main/README.md"
10
+ HELP_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/Q%26A/README.md"
11
+ COPYRIGHT_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/copyright/README.md"
12
+ CONTACT_URL = "https://forms.gle/mAUj1CdhufHFbiWs7"
13
+ TS_URL = "https://github.com/X1288664/LINE-Log-Manager-for-Hugging-face/blob/troubleshooting/README.md"
14
  JST = timezone(timedelta(hours=9))
15
 
16
+ def load_log_file(file, progress=gr.Progress()):
17
+ """アップロードされたログファイルを開き、内容を取得 + プログレスバー"""
18
  if not file:
19
  return None, "エラー(FILE-001): ファイルが選択されていません"
20
 
 
21
  if not file.name.endswith(".txt"):
22
  return None, "エラー(FILE-005): サポートされていないファイル形式です。TXTファイルを選択してください。"
23
+
24
  try:
25
  with open(file.name, "r", encoding="utf-8") as f:
26
+ lines = f.readlines()
27
+
28
+ # プログレスバー(ログファイル読み込み)
29
+ for i in progress.tqdm(range(1, 101), desc="ログファイルを読み込み中..."):
30
+ time.sleep(0.01) # 処理シミュレーション
31
+
32
+ return lines, None
33
  except Exception as e:
34
  return None, "エラー(FILE-004): ファイルのエンコード形式が不正です(UTF-8のみ対応)"
35
 
36
+ def search_logs(file, keyword, year, month, day, progress=gr.Progress()):
37
+ """ログ検索処理 + プログレスバー"""
38
  log_lines, error = load_log_file(file)
39
  if error:
40
+ return "", error, None
41
 
42
  if not log_lines:
43
  return "", "エラー(FILE-003): ファイルが空です。", None
44
 
 
45
  is_word_search = bool(keyword.strip())
46
  is_date_search = year != "----" and month != "----" and day != "----"
47
 
48
  if is_word_search and is_date_search:
49
  return "", "エラー(SEARCH-001): ワード検索と日付検索は同時に行えません。", None
50
 
 
51
  search_condition = "検索条件: なし"
52
  results = []
53
 
54
  if is_word_search:
55
  search_condition = f"検索条件: ワード[{keyword}]"
56
+ for line in progress.tqdm(log_lines, desc="検索中..."):
57
+ if keyword in line:
58
+ results.append(f"- {line.strip()}")
59
 
60
  elif is_date_search:
61
  try:
 
69
  return "", "エラー(SEARCH-002): 無効な日付形式です。", None
70
 
71
  formatted_results = "\n".join(results) if results else "SEARCH-003: 一致する結果が見つかりませんでした。"
 
72
  return formatted_results, f"{len(results)} 件の結果が見つかりました。", search_condition
73
 
74
+ def generate_download_link(results, search_condition, progress=gr.Progress()):
75
+ """エクスポート処理 + プログレスバ��"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  if not results:
77
  return "エラー(EXPORT-001): エクスポートするデータがありません。"
78
 
 
79
  execution_time = datetime.now(JST).strftime("%Y%m%d_%H%M%S")
 
 
80
  JPN_date = datetime.now(JST).strftime("%Y/%m/%d %H:%M:%S")
81
+
 
82
  if "ワード" in search_condition:
83
  condition_text = search_condition.replace("検索条件: ワード[", "").replace("]", "").replace(" ", "_")
84
  elif "日付" in search_condition:
 
98
  )
99
 
100
  encoded_file = base64.b64encode(file_content.encode()).decode()
 
 
101
 
102
+ # エクスポートの進捗を表示
103
+ for i in progress.tqdm(range(1, 101), desc="エクスポート処理中..."):
104
+ time.sleep(0.01)
105
 
106
+ href = f'<a href="data:text/plain;base64,{encoded_file}" download="{file_name}">結果をダウンロード</a>'
107
+ return href
108
 
109
  # Gradio UI
110
  with gr.Blocks() as demo:
 
112
 
113
  file_input = gr.File(label="ログファイルをアップロード")
114
 
 
115
  search_word = gr.Textbox(label="ユーザー検索ワード")
116
 
 
117
  year = gr.Dropdown(choices=["----"] + [str(y) for y in range(2020, 2041)], value="----", label="年")
118
  month = gr.Dropdown(choices=["----"] + [str(m) for m in range(1, 13)], value="----", label="月")
119
  day = gr.Dropdown(choices=["----"] + [str(d) for d in range(1, 32)], value="----", label="日")
 
124
 
125
  search_condition_state = gr.State()
126
 
 
127
  export_button = gr.Button("TXTをエクスポートする")
128
+ export_output = gr.HTML()
129
  export_status = gr.Textbox(label="エクスポートメッセージ", interactive=False)
130
 
131
  search_button.click(
 
146
  gr.Markdown(f"[🛠 サポート]({SUPPORT_URL})")
147
  gr.Markdown(f"[© コピーライト]({COPYRIGHT_URL})")
148
 
 
149
  demo.launch()