-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_web.py
More file actions
169 lines (149 loc) · 5.83 KB
/
main_web.py
File metadata and controls
169 lines (149 loc) · 5.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""
Browser-based UI for Photo Selection (no Tkinter required).
Run: python main_web.py
Then open http://127.0.0.1:5000 in your browser.
"""
import os
import sys
import threading
from io import StringIO
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
from flask import Flask, request, jsonify, render_template_string
app = Flask(__name__)
# In-memory log for the last run (simple single-run UI)
_job_log: list[str] = []
_job_done: bool = False
_job_error: str | None = None
HTML = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Photo Selector</title>
<style>
* { box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 560px; margin: 32px auto; padding: 0 16px; }
h1 { font-size: 1.4rem; margin-bottom: 20px; }
label { display: block; font-weight: 600; margin-top: 12px; margin-bottom: 4px; }
input[type="text"], input[type="password"] { width: 100%; padding: 8px 10px; font-size: 14px; border: 1px solid #ccc; border-radius: 6px; }
.hint { font-size: 12px; color: #666; margin-top: 2px; }
button { margin-top: 20px; padding: 12px 24px; font-size: 16px; font-weight: 600; background: #007AFF; color: white; border: none; border-radius: 8px; cursor: pointer; }
button:hover { background: #0056b3; }
button:disabled { background: #999; cursor: not-allowed; }
#log { margin-top: 20px; padding: 12px; background: #f5f5f5; border-radius: 8px; font-family: monospace; font-size: 12px; white-space: pre-wrap; max-height: 320px; overflow-y: auto; }
.err { color: #c00; }
.ok { color: #060; }
</style>
</head>
<body>
<h1>Photo Selector — Pick best photos with AI</h1>
<form id="form">
<label>OpenAI API Key</label>
<input type="password" name="api_key" placeholder="sk-..." required>
<label>Folder with photos (source)</label>
<input type="text" name="source" placeholder="/path/to/photos" required>
<span class="hint">Full path to the folder containing your images.</span>
<label>Folder for selected photos (destination)</label>
<input type="text" name="destination" placeholder="/path/to/selected" required>
<span class="hint">Full path where the 20 selected photos will be moved.</span>
<label>Phone number to notify when done</label>
<input type="text" name="phone" placeholder="+15551234567">
<span class="hint">Optional. For SMS you must also set Twilio credentials in .env (or leave blank).</span>
<button type="submit" id="btn">Run photo selection</button>
</form>
<div id="log"></div>
<script>
const form = document.getElementById('form');
const logEl = document.getElementById('log');
const btn = document.getElementById('btn');
function log(msg, isErr) {
const p = document.createElement('div');
p.className = isErr ? 'err' : '';
p.textContent = msg;
logEl.appendChild(p);
logEl.scrollTop = logEl.scrollHeight;
}
form.addEventListener('submit', async (e) => {
e.preventDefault();
logEl.innerHTML = '';
btn.disabled = true;
const fd = new FormData(form);
try {
const r = await fetch('/run', { method: 'POST', body: fd });
const data = await r.json();
if (data.error) { log(data.error, true); btn.disabled = false; return; }
log('Job started. Polling log...');
const interval = setInterval(async () => {
const lr = await fetch('/log');
const d = await lr.json();
logEl.innerHTML = '';
(d.lines || []).forEach(line => log(line));
if (d.done) { clearInterval(interval); btn.disabled = false; if (d.error) log(d.error, true); }
}, 800);
} catch (err) {
log(err.message, true);
btn.disabled = false;
}
});
</script>
</body>
</html>
"""
@app.route("/")
def index():
return render_template_string(HTML)
@app.route("/run", methods=["POST"])
def run():
global _job_log, _job_done, _job_error
_job_log = []
_job_done = False
_job_error = None
api_key = (request.form.get("api_key") or "").strip()
source = (request.form.get("source") or "").strip()
destination = (request.form.get("destination") or "").strip()
phone = (request.form.get("phone") or "").strip()
if not api_key:
return jsonify({"error": "Please enter your OpenAI API key."})
if not source:
return jsonify({"error": "Please enter the folder that contains your photos."})
if not destination:
return jsonify({"error": "Please enter the folder where selected photos should be saved."})
def capture_log(msg: str):
_job_log.append(msg)
def run_job():
global _job_done, _job_error
try:
os.environ["OPENAI_API_KEY"] = api_key
from main import run
run(
source,
destination_folder=destination,
twilio_to_number=phone or None,
twilio_account_sid=os.environ.get("TWILIO_ACCOUNT_SID") or None,
twilio_auth_token=os.environ.get("TWILIO_AUTH_TOKEN") or None,
twilio_from_number=os.environ.get("TWILIO_FROM_NUMBER") or None,
log=capture_log,
)
except Exception as e:
_job_error = str(e)
capture_log(str(e))
finally:
_job_done = True
threading.Thread(target=run_job, daemon=True).start()
return jsonify({"ok": True})
@app.route("/log")
def log():
return jsonify(
lines=_job_log,
done=_job_done,
error=_job_error,
)
if __name__ == "__main__":
print("Open in your browser: http://127.0.0.1:5000")
app.run(host="127.0.0.1", port=5000, debug=False, threaded=True)