Spaces:
Sleeping
Sleeping
| import os, json, threading | |
| from flask import Flask, request, jsonify, send_from_directory | |
| app = Flask(__name__) | |
| DATA_DIR = "/data" if os.path.isdir("/data") else "/app" | |
| COMMENTS_FILE = os.path.join(DATA_DIR, "comments.json") | |
| lock = threading.Lock() | |
| # Schema: { "problem_id": [ {text, author, timestamp}, ... ] } | |
| def load_comments(): | |
| with lock: | |
| if os.path.exists(COMMENTS_FILE): | |
| with open(COMMENTS_FILE) as f: | |
| data = json.load(f) | |
| # Migrate old format (single comment per problem) to list format | |
| if data and isinstance(next(iter(data.values()), None), dict): | |
| migrated = {} | |
| for pid, entry in data.items(): | |
| if isinstance(entry, dict) and "text" in entry: | |
| migrated[pid] = [entry] | |
| elif isinstance(entry, list): | |
| migrated[pid] = entry | |
| return migrated | |
| return data | |
| return {} | |
| def save_comments(comments): | |
| with lock: | |
| with open(COMMENTS_FILE, "w") as f: | |
| json.dump(comments, f, indent=2) | |
| def index(): | |
| return send_from_directory("/app", "index.html") | |
| def get_comments(): | |
| return jsonify(load_comments()) | |
| def post_comment(): | |
| body = request.json | |
| pid = body.get("problem_id") | |
| text = body.get("text", "").strip() | |
| author = body.get("author", "anonymous") | |
| timestamp = body.get("timestamp", "") | |
| comments = load_comments() | |
| if pid not in comments: | |
| comments[pid] = [] | |
| # Find existing comment by this author on this problem | |
| existing_idx = None | |
| for i, c in enumerate(comments[pid]): | |
| if c.get("author") == author: | |
| existing_idx = i | |
| break | |
| if text: | |
| entry = {"text": text, "author": author, "timestamp": timestamp} | |
| if existing_idx is not None: | |
| comments[pid][existing_idx] = entry | |
| else: | |
| comments[pid].append(entry) | |
| else: | |
| # Empty text = delete this author's comment | |
| if existing_idx is not None: | |
| comments[pid].pop(existing_idx) | |
| if not comments[pid]: | |
| del comments[pid] | |
| save_comments(comments) | |
| total = sum(len(v) for v in comments.values()) | |
| return jsonify({"ok": True, "count": total}) | |
| if __name__ == "__main__": | |
| print(f"Comments stored at: {COMMENTS_FILE}") | |
| app.run(host="0.0.0.0", port=7860) | |