GmailTrust commited on
Commit
4132e77
Β·
verified Β·
1 Parent(s): 5969399

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +173 -80
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  import re
3
  import gradio as gr
@@ -9,111 +10,205 @@ OUTPUT_FILE_TXT = "output.txt"
9
  OUTPUT_FILE_XLSX = "output.xlsx"
10
  TEMP_FILE = "temp.txt"
11
  TAKEN_ROWS_FILE = "taken_rows.txt"
12
- SECRET_KEY = os.environ.get("SECRET_KEY", "hihihaha") # fallback nαΊΏu chΖ°a set biαΊΏn
13
 
14
- # ==== File helpers ====
15
- def write_file(file_path, data):
16
- with open(file_path, 'w', encoding='utf-8') as file:
17
- file.writelines(data)
18
-
19
- def append_log(file_path, data):
20
- now_vn = datetime.utcnow() + timedelta(hours=7) # GMT+7
21
- with open(file_path, 'a', encoding='utf-8') as file:
22
- file.write(f"\n--- {now_vn.strftime('%Y-%m-%d %H:%M:%S')} ---\n")
23
- file.writelines(data)
24
-
25
- def read_file(file):
26
- if file is None:
27
- return ""
28
- try:
29
- with open(file, 'r', encoding='utf-8') as f:
30
- return f.read()
31
- except Exception as e:
32
- return f"Error reading file: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- # ==== Hidden data functions ====
35
- def view_hidden(password):
36
- if password != SECRET_KEY:
37
- return "❌ Wrong password!"
38
- if not os.path.exists(TEMP_FILE):
39
- return ""
40
- with open(TEMP_FILE, "r", encoding="utf-8") as f:
41
- content = f.read()
42
- return content if content.strip() else ""
43
 
44
- def clear_hidden(password):
45
- if password != SECRET_KEY:
46
- return "❌ Wrong password!"
47
- if os.path.exists(TEMP_FILE):
48
- os.remove(TEMP_FILE)
49
- return "βœ… Cleared."
50
  return ""
51
 
52
- # ==== Utils ====
53
- def count_emails(data):
54
- if not data or (isinstance(data, str) and data.startswith("Error")):
55
- return 0
56
- lines = [line.strip() for line in data.splitlines() if line.strip()]
57
- return len(lines)
58
 
59
- # ==== Core features ====
60
  def split_emails(input_data, uploaded_file):
61
- data = input_data if input_data else read_file(uploaded_file)
 
 
 
 
 
 
 
 
 
 
 
 
62
  if not data:
 
63
  return gr.update(label="Input Text (Total: 0)"), gr.update(value="", label="Output Text (Total: 0)"), None
 
 
 
 
 
 
 
 
64
  lines = data.splitlines()
65
- gmail_addresses = []
66
- for line in lines:
67
- match = re.search(r'([a-zA-Z0-9._%+-]+@gmail\.com)', line)
68
- if match:
69
- gmail_addresses.append(match.group(1) + '\n')
70
- append_log(TEMP_FILE, [line + '\n' for line in lines])
71
- output_data = "".join(gmail_addresses)
72
- return gr.update(value=data, label=f"Input Text (Total: {count_emails(data)})"), gr.update(value=output_data, label=f"Output Text (Total: {count_emails(output_data)})"), None
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  def fill_missing_parts(input_data, uploaded_file):
75
- data = input_data if input_data else read_file(uploaded_file)
 
 
 
 
 
 
 
 
 
 
 
76
  if not data:
77
  return gr.update(label="Input Text (Total: 0)"), gr.update(value="", label="Output Text (Total: 0)"), None
 
78
  if not os.path.exists(TEMP_FILE):
79
- return gr.update(label="Input Text (Total: 0)"), gr.update(value="", label="Output Text (Total: 0)"), None
80
- with open(TEMP_FILE, 'r', encoding='utf-8') as file:
81
- temp_lines = {line.strip() for line in file}
 
 
 
 
 
 
 
 
82
  input_emails = [line.strip() for line in data.splitlines() if line.strip()]
83
  output_lines = []
84
  for email in input_emails:
85
- cleaned_email = re.sub(r'^(live|good)\|', '', email.strip())
86
- found_line = next((line for line in temp_lines if cleaned_email in line), None)
87
- output_lines.append((found_line or cleaned_email) + '\n')
88
- output_data = "".join(output_lines)
89
- return gr.update(value=data, label=f"Input Text (Total: {count_emails(data)})"), gr.update(value=output_data, label=f"Output Text (Total: {count_emails(output_data)})"), None
 
 
 
90
 
91
  def clear_files():
92
- for file_path in [OUTPUT_FILE_TXT, OUTPUT_FILE_XLSX, TAKEN_ROWS_FILE]:
93
- if os.path.exists(file_path):
94
- os.remove(file_path)
95
  return gr.update(value="", label="Input Text (Total: 0)"), gr.update(value="", label="Output Text (Total: 0)"), None, None
96
 
97
  def download_output(input_data, output_data, uploaded_file):
98
  if not output_data:
 
99
  if os.path.exists(OUTPUT_FILE_TXT):
100
  os.remove(OUTPUT_FILE_TXT)
101
  if os.path.exists(OUTPUT_FILE_XLSX):
102
  os.remove(OUTPUT_FILE_XLSX)
103
- return gr.update(label=f"Input Text (Total: {count_emails(input_data)})"), gr.update(label=f"Output Text (Total: {count_emails(output_data)})"), None
 
 
104
  write_file(OUTPUT_FILE_TXT, output_data.splitlines(keepends=True))
105
- lines = output_data.splitlines()
106
- data_rows = []
107
- for line in lines:
108
- if line.strip():
109
- separator = re.search(r'[\t|;:]', line)
110
- if separator:
111
- parts = line.strip().split(separator.group())
112
- data_rows.append([p.strip() for p in parts])
113
- else:
114
- data_rows.append([line.strip()])
115
- pd.DataFrame(data_rows).to_excel(OUTPUT_FILE_XLSX, index=False, header=False)
116
- return gr.update(label=f"Input Text (Total: {count_emails(input_data)})"), gr.update(label=f"Output Text (Total: {count_emails(output_data)})"), [OUTPUT_FILE_TXT, OUTPUT_FILE_XLSX]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  # ==== UI ====
119
  with gr.Blocks(title="Email Processor", theme=gr.themes.Soft()) as demo:
@@ -133,24 +228,22 @@ with gr.Blocks(title="Email Processor", theme=gr.themes.Soft()) as demo:
133
  fill_btn = gr.Button("πŸ” Fill Missing")
134
  clear_files_btn = gr.Button("🧹 Clear All Data")
135
 
136
- with gr.Tab("πŸ“œ"): # tab icon only
137
  hidden_password = gr.Textbox(label="Password", type="password", placeholder="Enter password")
138
  view_btn = gr.Button("View")
139
  hidden_output = gr.Textbox(label="", lines=15, interactive=False)
140
  clear_btn = gr.Button("Clear")
141
 
142
- # Actions
143
  split_btn.click(split_emails, inputs=[input_text, upload_file], outputs=[input_text, output_text, download_file])
144
  fill_btn.click(fill_missing_parts, inputs=[input_text, upload_file], outputs=[input_text, output_text, download_file])
145
  clear_files_btn.click(clear_files, outputs=[input_text, output_text, download_file, upload_file])
146
 
147
- # Clear buttons with label reset
148
  clear_input_btn.click(lambda: gr.update(value="", label="Input Text (Total: 0)"), outputs=[input_text])
149
  clear_output_btn.click(lambda: gr.update(value="", label="Output Text (Total: 0)"), outputs=[output_text])
150
 
151
  download_btn.click(download_output, inputs=[input_text, output_text, upload_file], outputs=[input_text, output_text, download_file])
152
 
153
- # Hidden tab actions
154
  view_btn.click(view_hidden, inputs=[hidden_password], outputs=[hidden_output])
155
  clear_btn.click(clear_hidden, inputs=[hidden_password], outputs=[hidden_output])
156
 
 
1
+ # app.py
2
  import os
3
  import re
4
  import gradio as gr
 
10
  OUTPUT_FILE_XLSX = "output.xlsx"
11
  TEMP_FILE = "temp.txt"
12
  TAKEN_ROWS_FILE = "taken_rows.txt"
 
13
 
14
+ # Names of secret variables expected (you WILL set these in HF Settings -> Variables)
15
+ SECRET_VARS = ["SECRET_A", "SECRET_B", "SECRET_C", "SECRET_KEY"]
16
+
17
+ # placeholder for whether secrets loaded correctly
18
+ _secrets_loaded = True
19
+ _missing_secrets = []
20
+
21
+ # ==== Load secret parts (in order) ====
22
+ # Each secret should contain a snippet of Python code that defines needed functions.
23
+ # We try to exec them in global scope so their functions (e.g., extract_gmails, save_log) exist.
24
+ for name in SECRET_VARS:
25
+ val = os.environ.get(name)
26
+ if not val:
27
+ _secrets_loaded = False
28
+ _missing_secrets.append(name)
29
+ else:
30
+ try:
31
+ # Execute secret snippet in module globals
32
+ exec(val, globals())
33
+ except Exception as e:
34
+ # If exec fails, mark as missing and keep going
35
+ _secrets_loaded = False
36
+ _missing_secrets.append(f"{name} (exec error: {e})")
37
+
38
+ # After exec, we expect at least two functions to be defined by the secrets:
39
+ # - extract_gmails(lines: list[str]) -> list[str]
40
+ # - save_log(file_path: str, lines: list[str]) -> None
41
+ # and SECRET_KEY variable for password protection (already present as env)
42
+ SECRET_KEY = os.environ.get("SECRET_KEY", None)
43
+
44
+ _required_funcs = ["extract_gmails", "save_log"]
45
+ for fn in _required_funcs:
46
+ if fn not in globals():
47
+ _secrets_loaded = False
48
+ _missing_secrets.append(f"{fn} (function not defined)")
49
+
50
+ # ==== Helpers (non-secret, minimal) ====
51
+ def safe_count_lines(data):
52
+ if not data:
53
+ return 0
54
+ return len([l for l in data.splitlines() if l.strip()])
55
 
56
+ def write_file(file_path, data_lines):
57
+ with open(file_path, 'w', encoding='utf-8') as f:
58
+ f.writelines(data_lines)
 
 
 
 
 
 
59
 
60
+ def _make_config_error_text():
61
+ if _missing_secrets:
62
+ return "Configuration incomplete. Please set secret variables."
 
 
 
63
  return ""
64
 
65
+ # ==== Public features (UI-facing). These call secret functions when available. ====
 
 
 
 
 
66
 
 
67
  def split_emails(input_data, uploaded_file):
68
+ """
69
+ - Requires secret function: extract_gmails(lines)->list
70
+ - Requires secret function: save_log(file_path, lines)
71
+ """
72
+ # load raw data
73
+ data = input_data if input_data else ""
74
+ if not data and uploaded_file:
75
+ try:
76
+ with open(uploaded_file.name, "r", encoding="utf-8") as f:
77
+ data = f.read()
78
+ except Exception:
79
+ data = ""
80
+
81
  if not data:
82
+ # return (input_update, output_update, download_placeholder)
83
  return gr.update(label="Input Text (Total: 0)"), gr.update(value="", label="Output Text (Total: 0)"), None
84
+
85
+ if not _secrets_loaded:
86
+ # Configuration missing β€” do not run secret logic
87
+ return (gr.update(value=data, label=f"Input Text (Total: {safe_count_lines(data)})"),
88
+ gr.update(value=_make_config_error_text(), label="Output Text (Total: 0)"),
89
+ None)
90
+
91
+ # At this point, secrets were loaded and extract_gmails & save_log should exist
92
  lines = data.splitlines()
93
+ try:
94
+ gmails = extract_gmails(lines) # secret function (must return list of strings ending with '\n' or plain items)
95
+ except Exception as e:
96
+ return (gr.update(value=data, label=f"Input Text (Total: {safe_count_lines(data)})"),
97
+ gr.update(value=f"Error processing: {e}", label="Output Text (Total: 0)"),
98
+ None)
99
+
100
+ # Save log via secret save_log function (may include timezone handling)
101
+ try:
102
+ save_log(TEMP_FILE, [l + "\n" for l in lines])
103
+ except Exception as e:
104
+ # If logging fails, do not crash β€” report minimal msg
105
+ return (gr.update(value=data, label=f"Input Text (Total: {safe_count_lines(data)})"),
106
+ gr.update(value=f"Error saving (config?): {e}", label="Output Text (Total: 0)"),
107
+ None)
108
+
109
+ output_data = "".join(gmails)
110
+ return (gr.update(value=data, label=f"Input Text (Total: {safe_count_lines(data)})"),
111
+ gr.update(value=output_data, label=f"Output Text (Total: {safe_count_lines(output_data)})"),
112
+ None)
113
 
114
  def fill_missing_parts(input_data, uploaded_file):
115
+ """
116
+ - Uses TEMP_FILE as source of saved lines (depends on secret save_log implementation writing human-readable lines)
117
+ - Performs lookup via cleaned input and lines in TEMP_FILE
118
+ """
119
+ data = input_data if input_data else ""
120
+ if not data and uploaded_file:
121
+ try:
122
+ with open(uploaded_file.name, "r", encoding="utf-8") as f:
123
+ data = f.read()
124
+ except Exception:
125
+ data = ""
126
+
127
  if not data:
128
  return gr.update(label="Input Text (Total: 0)"), gr.update(value="", label="Output Text (Total: 0)"), None
129
+
130
  if not os.path.exists(TEMP_FILE):
131
+ return (gr.update(value=data, label=f"Input Text (Total: {safe_count_lines(data)})"),
132
+ gr.update(value="", label="Output Text (Total: 0)"),
133
+ None)
134
+
135
+ # read temp file
136
+ try:
137
+ with open(TEMP_FILE, "r", encoding="utf-8") as f:
138
+ temp_lines = {line.strip() for line in f if line.strip()}
139
+ except Exception:
140
+ temp_lines = set()
141
+
142
  input_emails = [line.strip() for line in data.splitlines() if line.strip()]
143
  output_lines = []
144
  for email in input_emails:
145
+ cleaned = re.sub(r'^(live|good)\|', '', email.strip())
146
+ found = next((line for line in temp_lines if cleaned in line), None)
147
+ output_lines.append((found or cleaned) + "\n")
148
+
149
+ out = "".join(output_lines)
150
+ return (gr.update(value=data, label=f"Input Text (Total: {safe_count_lines(data)})"),
151
+ gr.update(value=out, label=f"Output Text (Total: {safe_count_lines(out)})"),
152
+ None)
153
 
154
  def clear_files():
155
+ for p in [OUTPUT_FILE_TXT, OUTPUT_FILE_XLSX, TAKEN_ROWS_FILE]:
156
+ if os.path.exists(p):
157
+ os.remove(p)
158
  return gr.update(value="", label="Input Text (Total: 0)"), gr.update(value="", label="Output Text (Total: 0)"), None, None
159
 
160
  def download_output(input_data, output_data, uploaded_file):
161
  if not output_data:
162
+ # remove any existing output files if no data
163
  if os.path.exists(OUTPUT_FILE_TXT):
164
  os.remove(OUTPUT_FILE_TXT)
165
  if os.path.exists(OUTPUT_FILE_XLSX):
166
  os.remove(OUTPUT_FILE_XLSX)
167
+ return gr.update(label=f"Input Text (Total: {safe_count_lines(input_data)})"), gr.update(label=f"Output Text (Total: {safe_count_lines(output_data)})"), None
168
+
169
+ # write output.txt
170
  write_file(OUTPUT_FILE_TXT, output_data.splitlines(keepends=True))
171
+
172
+ # build xlsx
173
+ rows = []
174
+ for line in output_data.splitlines():
175
+ if not line.strip():
176
+ continue
177
+ sep = re.search(r'[\t|;:]', line)
178
+ if sep:
179
+ parts = line.strip().split(sep.group())
180
+ rows.append([p.strip() for p in parts])
181
+ else:
182
+ rows.append([line.strip()])
183
+
184
+ pd.DataFrame(rows).to_excel(OUTPUT_FILE_XLSX, index=False, header=False)
185
+ return gr.update(label=f"Input Text (Total: {safe_count_lines(input_data)})"), gr.update(label=f"Output Text (Total: {safe_count_lines(output_data)})"), [OUTPUT_FILE_TXT, OUTPUT_FILE_XLSX]
186
+
187
+ # ==== Hidden view/clear handlers (password protected by SECRET_KEY) ====
188
+ def view_hidden(password):
189
+ if SECRET_KEY is None:
190
+ return "" # no secret configured
191
+ if password != SECRET_KEY:
192
+ return "❌"
193
+ if not os.path.exists(TEMP_FILE):
194
+ return ""
195
+ try:
196
+ with open(TEMP_FILE, "r", encoding="utf-8") as f:
197
+ return f.read()
198
+ except Exception:
199
+ return ""
200
+
201
+ def clear_hidden(password):
202
+ if SECRET_KEY is None:
203
+ return ""
204
+ if password != SECRET_KEY:
205
+ return "❌"
206
+ try:
207
+ if os.path.exists(TEMP_FILE):
208
+ os.remove(TEMP_FILE)
209
+ return "βœ…"
210
+ except Exception:
211
+ return ""
212
 
213
  # ==== UI ====
214
  with gr.Blocks(title="Email Processor", theme=gr.themes.Soft()) as demo:
 
228
  fill_btn = gr.Button("πŸ” Fill Missing")
229
  clear_files_btn = gr.Button("🧹 Clear All Data")
230
 
231
+ with gr.Tab("πŸ“œ"): # only icon
232
  hidden_password = gr.Textbox(label="Password", type="password", placeholder="Enter password")
233
  view_btn = gr.Button("View")
234
  hidden_output = gr.Textbox(label="", lines=15, interactive=False)
235
  clear_btn = gr.Button("Clear")
236
 
237
+ # Bindings
238
  split_btn.click(split_emails, inputs=[input_text, upload_file], outputs=[input_text, output_text, download_file])
239
  fill_btn.click(fill_missing_parts, inputs=[input_text, upload_file], outputs=[input_text, output_text, download_file])
240
  clear_files_btn.click(clear_files, outputs=[input_text, output_text, download_file, upload_file])
241
 
 
242
  clear_input_btn.click(lambda: gr.update(value="", label="Input Text (Total: 0)"), outputs=[input_text])
243
  clear_output_btn.click(lambda: gr.update(value="", label="Output Text (Total: 0)"), outputs=[output_text])
244
 
245
  download_btn.click(download_output, inputs=[input_text, output_text, upload_file], outputs=[input_text, output_text, download_file])
246
 
 
247
  view_btn.click(view_hidden, inputs=[hidden_password], outputs=[hidden_output])
248
  clear_btn.click(clear_hidden, inputs=[hidden_password], outputs=[hidden_output])
249