forked from TheLime1/infinite-ai-web
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
215 lines (185 loc) · 7.15 KB
/
Copy pathutils.py
File metadata and controls
215 lines (185 loc) · 7.15 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import os
import json
from config import WEB_DIR
def save_to_cache(path, content_type, content):
"""Save generated content to cache in web directory"""
try:
# Normalize path
if path.startswith('/'):
path = path[1:]
path = path.rstrip('/')
if path == '':
path = 'index'
# Determine file extension based on content type
if content_type == 'text/html':
extension = '.html'
elif content_type == 'application/json':
extension = '.json'
elif content_type.startswith('text/'):
extension = '.txt'
else:
extension = '.html' # default to HTML if unknown
# Always add extension to the filename
if '/' in path:
dir_path = os.path.join(WEB_DIR, os.path.dirname(path))
file_name = os.path.basename(path)
file_path = os.path.join(dir_path, f"{file_name}{extension}")
else:
file_path = os.path.join(WEB_DIR, f"{path}{extension}")
# Create directory if it doesn't exist
os.makedirs(os.path.dirname(file_path), exist_ok=True)
# Save content to file
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
print(f"Content cached to: {file_path}")
return True
except Exception as e:
print(f"Error caching content: {e}")
return False
def load_from_cache(path):
"""Load content from cache if exists"""
try:
# Normalize path
if path.startswith('/'):
path = path[1:]
path = path.rstrip('/')
if path == '':
path = 'index'
# Try different extensions
possible_paths = []
if '/' in path:
# For nested paths like "games/stronghold"
dir_path = os.path.join(WEB_DIR, os.path.dirname(path))
file_name = os.path.basename(path)
possible_paths.extend([
os.path.join(dir_path, f"{file_name}.html"), # .html files
os.path.join(dir_path, f"{file_name}.json"), # .json files
os.path.join(dir_path, f"{file_name}.txt"), # .txt files
os.path.join(dir_path, file_name), # no extension (legacy)
])
else:
# For top-level paths like "programming"
possible_paths.extend([
os.path.join(WEB_DIR, f"{path}.html"),
os.path.join(WEB_DIR, f"{path}.json"),
os.path.join(WEB_DIR, f"{path}.txt"),
os.path.join(WEB_DIR, path),
])
for file_path in possible_paths:
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Determine content type from extension
if file_path.endswith('.html'):
content_type = 'text/html'
elif file_path.endswith('.json'):
content_type = 'application/json'
elif file_path.endswith('.txt'):
content_type = 'text/plain'
else:
content_type = 'text/html' # default
print(f"Content loaded from cache: {file_path}")
return content_type, content
return None, None
except Exception as e:
print(f"Error loading from cache: {e}")
return None, None
def is_cached(path):
"""Check if content is cached"""
content_type, content = load_from_cache(path)
return content is not None
def clear_cache_for_path(path):
"""Clear cache for specific path"""
try:
# Normalize path
if path.startswith('/'):
path = path[1:]
if path == '':
path = 'index'
# Possible cache file paths
possible_paths = []
if '/' in path:
# For nested paths
dir_path = os.path.join(WEB_DIR, os.path.dirname(path))
file_name = os.path.basename(path)
possible_paths.extend([
os.path.join(dir_path, f"{file_name}.html"),
os.path.join(dir_path, f"{file_name}.json"),
os.path.join(dir_path, f"{file_name}.txt"),
os.path.join(dir_path, file_name),
])
else:
# For top-level paths
possible_paths.extend([
os.path.join(WEB_DIR, f"{path}.html"),
os.path.join(WEB_DIR, f"{path}.json"),
os.path.join(WEB_DIR, f"{path}.txt"),
os.path.join(WEB_DIR, path),
])
# Also add directory index paths
possible_paths.append(os.path.join(WEB_DIR, path, "index.html"))
removed_count = 0
for file_path in possible_paths:
if os.path.exists(file_path):
os.remove(file_path)
print(f"Removed cache: {file_path}")
removed_count += 1
# Also remove directory if empty
dir_path = os.path.join(WEB_DIR, path)
if os.path.exists(dir_path) and os.path.isdir(dir_path):
try:
os.rmdir(dir_path)
print(f"Removed empty directory: {dir_path}")
except OSError:
pass # Directory not empty
return removed_count > 0
except Exception as e:
print(f"Error clearing cache for path: {e}")
return False
def get_cache_stats():
"""Get cache statistics"""
total_files = 0
total_size = 0
for root, dirs, files in os.walk(WEB_DIR):
for file in files:
file_path = os.path.join(root, file)
total_files += 1
total_size += os.path.getsize(file_path)
return {
'total_files': total_files,
'total_size_bytes': total_size,
'total_size_mb': round(total_size / (1024 * 1024), 2),
'cache_location': WEB_DIR
}
def save_html_response(path, content):
"""Legacy function - now uses save_to_cache"""
return save_to_cache(path, 'text/html', content)
def generate_index_html():
"""Generate the index.html file in root directory (legacy)"""
index_content = """<!DOCTYPE html>
<html>
<head>
<title>AI Generated Content Index</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; }
ul { list-style-type: none; padding: 0; }
li { margin: 10px 0; }
a { text-decoration: none; color: #0066cc; }
a:hover { text-decoration: underline; }
</style>
</head>
<body>
<h1>AI Generated Content Index</h1>
<p>This is an auto-generated index of all created pages.</p>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/search">Search</a></li>
</ul>
<p>Use the search functionality to generate new content.</p>
</body>
</html>"""
index_path = os.path.join(os.path.dirname(WEB_DIR), "index.html")
with open(index_path, "w", encoding="utf-8") as f:
f.write(index_content)
print("Generated index.html")