SPARC64 commited on
Commit
5a6637a
·
verified ·
1 Parent(s): 0cd6c25

Update app.py

Browse files

Rewrite all codes

Files changed (1) hide show
  1. app.py +34 -38
app.py CHANGED
@@ -3,15 +3,14 @@ import re
3
  import os
4
  from datetime import datetime, timedelta, timezone
5
 
 
6
  SUPPORT_URL = "https://chat.openai.com"
7
-
8
- # 日本時間の設定
9
  JST = timezone(timedelta(hours=9))
10
 
11
  def load_log_file(file):
12
- """アップロードされたログファイルを開いて内容を取得"""
13
- if file is None:
14
- return None, "ファイルが選択されていません。"
15
 
16
  try:
17
  with open(file.name, "r", encoding="utf-8") as f:
@@ -24,47 +23,44 @@ def search_logs(file, search_word, year, month, day):
24
  """ログを検索し、結果を返す"""
25
  log_lines, error = load_log_file(file)
26
  if error:
27
- return "", "エラー: " + error, None, "検索条件: なし"
28
 
29
  if not log_lines:
30
- return "", "ログファイルを先に読み込んでください。", None, "検索条件: なし"
31
-
32
- # 検索条件の設定(Noneにならないよう修正)
33
- search_condition = "検索条件: なし"
34
- if search_word.strip():
35
- search_condition = f"検索条件: ワード[{search_word}]"
36
- elif year != "----" and month != "----" and day != "----":
37
- search_condition = f"検索条件: 日付[{year}/{month}/{day}]"
38
-
39
- # 両方の検索条件が入力されている場合はエラーを返す
40
- if search_word.strip() and (year != "----" and month != "----" and day != "----"):
41
- return "", "エラー: ユーザー検索と日付検索を同時に行うことはできません。", None, "検索条件: なし"
42
 
 
 
 
 
 
43
  results = []
44
 
45
- # ユーザー検索
46
- if search_word.strip():
47
  results = [f"- {line.strip()}" for line in log_lines if search_word in line]
48
-
49
- # 日付検索
50
- elif year != "----" and month != "----" and day != "----":
51
  try:
52
  search_date = f"{year}/{month}/{day}"
53
  start_date = datetime.strptime(search_date, "%Y/%m/%d")
54
  end_date = start_date + timedelta(days=1)
 
55
  results = extract_date_range_logs(log_lines, start_date, end_date)
56
  results = [f"- {line.strip()}" for line in results]
57
  except ValueError:
58
- return "", "無効な日付形式です。", None, "検索条件: なし"
59
 
60
- # 検索結果を1行ずつ箇条書きで表示
61
  formatted_results = "\n".join(results) if results else "一致する結果が見つかりませんでした。"
62
-
63
  return formatted_results, f"{len(results)} 件の結果が見つかりました。", formatted_results, search_condition
64
 
65
  def extract_date_range_logs(lines, start_date, end_date):
66
  """指定された日付範囲のログを抽出する"""
67
- result = []
68
  current_date = None
69
 
70
  for line in lines:
@@ -76,9 +72,9 @@ def extract_date_range_logs(lines, start_date, end_date):
76
  continue
77
 
78
  if current_date and start_date <= current_date < end_date:
79
- result.append(line.strip())
80
 
81
- return result
82
 
83
  def export_results(results, search_condition):
84
  """検索結果をTXTファイルとしてエクスポート"""
@@ -86,7 +82,7 @@ def export_results(results, search_condition):
86
  return None, "エラー: エクスポートするデータがありません。"
87
 
88
  filename = f"search_results_{datetime.now(JST).strftime('%Y%m%d_%H%M%S')}.txt"
89
- file_path = os.path.join("/tmp", filename) # 一時ディレクトリに保存
90
 
91
  execution_date = datetime.now(JST).strftime("%Y/%m/%d %H:%M:%S")
92
 
@@ -96,23 +92,23 @@ def export_results(results, search_condition):
96
  f.write(f"検索実行日: {execution_date}\n")
97
  f.write(f"{search_condition}\n")
98
  f.write(f"ヒット件数: {len(results.splitlines())} 件\n")
99
- f.write("-" * 40 + "\n") # 区切り線
100
- f.write(results + "\n") # 必ず1行ずつ箇条書き
101
-
102
  return file_path, "TXTファイルのダウンロードが可能になりました。"
103
  except Exception as e:
104
  return None, f"エラー: {str(e)}"
105
 
106
- # Gradio UIの作成
107
  with gr.Blocks() as demo:
108
  gr.Markdown("# LINEログマネージャー - Hugging Face版")
109
 
110
  file_input = gr.File(label="ログファイルをアップロード")
111
 
112
- # ユーザー検索用のテキストボックス
113
  search_word = gr.Textbox(label="ユーザー検索ワード")
114
 
115
- # 日付検索用のドロップダウン
116
  year = gr.Dropdown(choices=["----"] + [str(y) for y in range(2020, 2041)], value="----", label="年")
117
  month = gr.Dropdown(choices=["----"] + [str(m) for m in range(1, 13)], value="----", label="月")
118
  day = gr.Dropdown(choices=["----"] + [str(d) for d in range(1, 32)], value="----", label="日")
@@ -122,8 +118,8 @@ with gr.Blocks() as demo:
122
  result_message = gr.Textbox(label="ステータス", interactive=False)
123
 
124
  # エクスポート機能
125
- export_button = gr.Button("TXTをエクスポートする") # 常に同じ表示
126
- export_output = gr.File(label="ダウンロード", interactive=False) # [サイズ]ではなく[ダウンロード]に変更
127
  export_status = gr.Textbox(label="エクスポートメッセージ", interactive=False)
128
 
129
  search_button.click(
 
3
  import os
4
  from datetime import datetime, timedelta, timezone
5
 
6
+ # 設定
7
  SUPPORT_URL = "https://chat.openai.com"
 
 
8
  JST = timezone(timedelta(hours=9))
9
 
10
  def load_log_file(file):
11
+ """アップロードされたログファイルを開き、内容を取得"""
12
+ if not file:
13
+ return None, "エラー: ファイルが選択されていません。"
14
 
15
  try:
16
  with open(file.name, "r", encoding="utf-8") as f:
 
23
  """ログを検索し、結果を返す"""
24
  log_lines, error = load_log_file(file)
25
  if error:
26
+ return "", error, None, "検索条件: なし"
27
 
28
  if not log_lines:
29
+ return "", "エラー: ログファイルが空です。", None, "検索条件: なし"
30
+
31
+ # 検索条件のチェック
32
+ is_word_search = bool(search_word.strip())
33
+ is_date_search = year != "----" and month != "----" and day != "----"
 
 
 
 
 
 
 
34
 
35
+ if is_word_search and is_date_search:
36
+ return "", "エラー: ワード検索と日付検索は同時に行えません。", None, "検索条件: なし"
37
+
38
+ # 検索条件の設定
39
+ search_condition = "検索条件: なし"
40
  results = []
41
 
42
+ if is_word_search:
43
+ search_condition = f"検索条件: ワード[{search_word}]"
44
  results = [f"- {line.strip()}" for line in log_lines if search_word in line]
45
+
46
+ elif is_date_search:
 
47
  try:
48
  search_date = f"{year}/{month}/{day}"
49
  start_date = datetime.strptime(search_date, "%Y/%m/%d")
50
  end_date = start_date + timedelta(days=1)
51
+ search_condition = f"検索条件: 日付[{search_date}]"
52
  results = extract_date_range_logs(log_lines, start_date, end_date)
53
  results = [f"- {line.strip()}" for line in results]
54
  except ValueError:
55
+ return "", "エラー: 無効な日付形式です。", None, "検索条件: なし"
56
 
 
57
  formatted_results = "\n".join(results) if results else "一致する結果が見つかりませんでした。"
58
+
59
  return formatted_results, f"{len(results)} 件の結果が見つかりました。", formatted_results, search_condition
60
 
61
  def extract_date_range_logs(lines, start_date, end_date):
62
  """指定された日付範囲のログを抽出する"""
63
+ results = []
64
  current_date = None
65
 
66
  for line in lines:
 
72
  continue
73
 
74
  if current_date and start_date <= current_date < end_date:
75
+ results.append(line.strip())
76
 
77
+ return results
78
 
79
  def export_results(results, search_condition):
80
  """検索結果をTXTファイルとしてエクスポート"""
 
82
  return None, "エラー: エクスポートするデータがありません。"
83
 
84
  filename = f"search_results_{datetime.now(JST).strftime('%Y%m%d_%H%M%S')}.txt"
85
+ file_path = os.path.join("/tmp", filename)
86
 
87
  execution_date = datetime.now(JST).strftime("%Y/%m/%d %H:%M:%S")
88
 
 
92
  f.write(f"検索実行日: {execution_date}\n")
93
  f.write(f"{search_condition}\n")
94
  f.write(f"ヒット件数: {len(results.splitlines())} 件\n")
95
+ f.write("-" * 40 + "\n")
96
+ f.write(results + "\n")
97
+
98
  return file_path, "TXTファイルのダウンロードが可能になりました。"
99
  except Exception as e:
100
  return None, f"エラー: {str(e)}"
101
 
102
+ # Gradio UI
103
  with gr.Blocks() as demo:
104
  gr.Markdown("# LINEログマネージャー - Hugging Face版")
105
 
106
  file_input = gr.File(label="ログファイルをアップロード")
107
 
108
+ # ユーザー検索用テキストボックス
109
  search_word = gr.Textbox(label="ユーザー検索ワード")
110
 
111
+ # 日付検索用ドロップダウン
112
  year = gr.Dropdown(choices=["----"] + [str(y) for y in range(2020, 2041)], value="----", label="年")
113
  month = gr.Dropdown(choices=["----"] + [str(m) for m in range(1, 13)], value="----", label="月")
114
  day = gr.Dropdown(choices=["----"] + [str(d) for d in range(1, 32)], value="----", label="日")
 
118
  result_message = gr.Textbox(label="ステータス", interactive=False)
119
 
120
  # エクスポート機能
121
+ export_button = gr.Button("TXTをエクスポートする")
122
+ export_output = gr.File(label="ダウンロード", interactive=False)
123
  export_status = gr.Textbox(label="エクスポートメッセージ", interactive=False)
124
 
125
  search_button.click(