-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflask_app.py
More file actions
145 lines (126 loc) · 5.13 KB
/
flask_app.py
File metadata and controls
145 lines (126 loc) · 5.13 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
"""Main API for Condado de Castilla.
This Flask application exposes endpoints for resources, chat integration and
forum comments. It is the primary backend used by the project and is exercised
by the test suite. ``nuevaweb/flask_app.py`` is a separate minimal demo and does
not replace this module.
"""
from flask import Flask, request, jsonify
from flask_caching import Cache
from graph_db_interface import GraphDBInterface
import os
import subprocess
import sqlite3
import json
app = Flask(__name__)
cache = Cache(app, config={
'CACHE_TYPE': 'SimpleCache',
'CACHE_DEFAULT_TIMEOUT': 60
})
db = GraphDBInterface()
def get_forum_comments_from_db():
"""Return forum comments grouped by agent as a dict."""
db_path = os.getenv('TEST_SQLITE_PATH') or os.path.join(os.path.dirname(__file__), 'forum.db')
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
conn.execute(
"CREATE TABLE IF NOT EXISTS forum_comments (id INTEGER PRIMARY KEY AUTOINCREMENT, agent TEXT NOT NULL, comment TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"
)
rows = conn.execute('SELECT agent, comment, created_at FROM forum_comments ORDER BY created_at DESC').fetchall()
comments = {}
for row in rows:
comments.setdefault(row['agent'], []).append({'comment': row['comment'], 'created_at': row['created_at']})
conn.close()
return comments
def get_forum_agents():
"""Return forum agents from config/forum_agents.json"""
path = os.path.join(os.path.dirname(__file__), 'config', 'forum_agents.json')
try:
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception:
return {}
@app.route('/api/resource', methods=['GET', 'POST'])
def resource_collection():
if request.method == 'POST':
data = request.get_json(silent=True) or {}
if not data.get('url'):
return jsonify({'error': "'url' field is required"}), 400
db.add_or_update_resource(data)
cache.delete('all_resources')
return jsonify({'success': True}), 201
else: # GET
resources = cache.get('all_resources')
if resources is None:
resources = db.get_all_resources()
cache.set('all_resources', resources)
return jsonify(resources)
@app.route('/api/chat', methods=['POST'])
def chat_handler():
data = request.get_json(silent=True) or {}
prompt = str(data.get('prompt', '')).strip()
if not prompt:
return jsonify({'error': "'prompt' field is required"}), 400
script_path = os.path.join(os.path.dirname(__file__), 'scripts', 'chat_cli.php')
try:
result = subprocess.run(
['php', script_path, prompt],
capture_output=True,
text=True,
check=False
)
if result.returncode != 0:
error_msg = result.stderr.strip() or 'Unknown error'
return jsonify({'error': f'PHP error: {error_msg}'}), 500
return jsonify({'response': result.stdout.strip()})
except Exception as exc:
return jsonify({'error': str(exc)}), 500
@app.route('/api/forum/agents', methods=['GET'])
def forum_agents_handler():
try:
agents = get_forum_agents()
return jsonify(agents)
except Exception as exc:
return jsonify({'error': str(exc)}), 500
@app.route('/api/forum/comments', methods=['GET', 'POST'])
def forum_comments_handler():
if request.method == 'POST':
data = request.get_json(silent=True) or {}
agent = str(data.get('agent', '')).strip()
comment = str(data.get('comment', '')).strip()
if not agent or not comment:
return jsonify({'error': "'agent' and 'comment' are required"}), 400
script_path = os.path.join(os.path.dirname(__file__), 'ajax_actions', 'save_comment.php')
try:
result = subprocess.run(
['php', script_path, agent, comment],
capture_output=True,
text=True,
check=False
)
if result.returncode != 0:
error_msg = result.stderr.strip() or result.stdout.strip() or 'Unknown error'
return jsonify({'error': f'PHP error: {error_msg}'}), 500
return jsonify({'success': True})
except Exception as exc:
return jsonify({'error': str(exc)}), 500
else:
try:
comments = get_forum_comments_from_db()
return jsonify(comments)
except Exception as exc:
return jsonify({'error': str(exc)}), 500
@app.route('/api/mission', methods=['GET'])
def mission_handler():
"""Return mission text from docs/README.md lines 3-7."""
try:
readme_path = os.path.join(os.path.dirname(__file__), 'docs', 'README.md')
with open(readme_path, 'r', encoding='utf-8') as f:
lines = f.readlines()[2:7]
text = ''.join(lines).strip()
return jsonify({'mission': text})
except Exception as exc:
return jsonify({'error': str(exc)}), 500
if __name__ == '__main__':
debug_env = os.getenv('FLASK_DEBUG')
debug_mode = str(debug_env).lower() in ('1', 'true')
app.run(debug=debug_mode)