Ramasani commited on
Commit
10032c3
·
1 Parent(s): cc39b72

Add frontend UI with static files and serve index route

Browse files
Files changed (4) hide show
  1. app.py +8 -0
  2. static/app.js +199 -0
  3. static/index.html +93 -0
  4. static/style.css +260 -0
app.py CHANGED
@@ -5,6 +5,7 @@ from typing import List, Optional
5
  from contextlib import asynccontextmanager
6
  from fastapi import FastAPI, HTTPException, BackgroundTasks, Request
7
  from fastapi.middleware.cors import CORSMiddleware
 
8
  from pydantic import BaseModel, HttpUrl
9
  from config import config
10
  from storage import db
@@ -69,6 +70,8 @@ app = FastAPI(
69
  lifespan=lifespan
70
  )
71
 
 
 
72
  app.add_middleware(
73
  CORSMiddleware,
74
  allow_origins=["*"],
@@ -78,6 +81,11 @@ app.add_middleware(
78
  )
79
 
80
 
 
 
 
 
 
81
  @app.get("/health")
82
  async def health_check():
83
  return {"status": "healthy", "service": "web-scraper"}
 
5
  from contextlib import asynccontextmanager
6
  from fastapi import FastAPI, HTTPException, BackgroundTasks, Request
7
  from fastapi.middleware.cors import CORSMiddleware
8
+ from fastapi.staticfiles import StaticFiles
9
  from pydantic import BaseModel, HttpUrl
10
  from config import config
11
  from storage import db
 
70
  lifespan=lifespan
71
  )
72
 
73
+ app.mount("/static", StaticFiles(directory="static"), name="static")
74
+
75
  app.add_middleware(
76
  CORSMiddleware,
77
  allow_origins=["*"],
 
81
  )
82
 
83
 
84
+ @app.get("/", include_in_schema=False)
85
+ async def serve_index():
86
+ from fastapi.responses import FileResponse
87
+ return FileResponse("static/index.html")
88
+
89
  @app.get("/health")
90
  async def health_check():
91
  return {"status": "healthy", "service": "web-scraper"}
static/app.js ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ document.addEventListener('DOMContentLoaded', () => {
2
+ const tabBtns = document.querySelectorAll('.tab-btn')
3
+ const tabContents = document.querySelectorAll('.tab-content')
4
+
5
+ tabBtns.forEach(btn => {
6
+ btn.addEventListener('click', () => {
7
+ tabBtns.forEach(b => b.classList.remove('active'))
8
+ tabContents.forEach(c => c.classList.remove('active'))
9
+
10
+ btn.classList.add('active')
11
+ document.getElementById(btn.dataset.tab).classList.add('active')
12
+ })
13
+ })
14
+
15
+ document.getElementById('scrape-form').addEventListener('submit', async (e) => {
16
+ e.preventDefault()
17
+ const urlsText = document.getElementById('urls').value
18
+ const urls = urlsText.split('\n').map(u => u.trim()).filter(u => u)
19
+
20
+ if (!urls.length) return
21
+
22
+ const result = document.getElementById('scrape-result')
23
+ result.textContent = 'Submitting...'
24
+
25
+ try {
26
+ const res = await fetch('/scrape', {
27
+ method: 'POST',
28
+ headers: { 'Content-Type': 'application/json' },
29
+ body: JSON.stringify({ urls })
30
+ })
31
+ const data = await res.json()
32
+ result.innerHTML = `<p>Job ID: <strong>${data.job_id}</strong></p><p>Status: ${data.status}</p><p>Total URLs: ${data.total}</p>`
33
+ } catch (err) {
34
+ result.innerHTML = `<p class="error">Error: ${err.message}</p>`
35
+ }
36
+ })
37
+
38
+ document.getElementById('check-job-btn').addEventListener('click', async () => {
39
+ const jobId = document.getElementById('job-id-input').value.trim()
40
+ if (!jobId) return
41
+
42
+ const result = document.getElementById('job-result')
43
+ result.textContent = 'Loading...'
44
+
45
+ try {
46
+ const res = await fetch(`/scrape/${jobId}`)
47
+ const data = await res.json()
48
+
49
+ let html = `<p>Status: ${data.status}</p><p>Progress: ${data.completed}/${data.total}</p>`
50
+ if (data.results) {
51
+ html += '<h3>Results:</h3><ul>'
52
+ data.results.forEach(r => {
53
+ html += `<li>${r.url} - ${r.error || r.title || 'No title'}</li>`
54
+ })
55
+ html += '</ul>'
56
+ }
57
+ result.innerHTML = html
58
+ } catch (err) {
59
+ result.innerHTML = `<p class="error">Error: ${err.message}</p>`
60
+ }
61
+ })
62
+
63
+ async function loadPages() {
64
+ const status = document.getElementById('status-filter').value
65
+ const tbody = document.querySelector('#pages-table tbody')
66
+ tbody.innerHTML = '<tr><td colspan="5">Loading...</td></tr>'
67
+
68
+ try {
69
+ const url = status ? `/pages?status=${status}` : '/pages'
70
+ const res = await fetch(url)
71
+ const pages = await res.json()
72
+
73
+ tbody.innerHTML = pages.map(p => `
74
+ <tr>
75
+ <td>${p.id}</td>
76
+ <td><a href="#" onclick="showPageDetail(${p.id}); return false">${truncate(p.url, 50)}</a></td>
77
+ <td>${p.title || '-'}</td>
78
+ <td>${p.prediction ? `<span class="category ${p.prediction.category}">${p.prediction.category}</span>` : '-'}</td>
79
+ <td>${p.error ? `<span class="error">${p.error}</span>` : '<span class="success">OK</span>'}</td>
80
+ </tr>
81
+ `).join('') || '<tr><td colspan="5">No pages found</td></tr>'
82
+ } catch (err) {
83
+ tbody.innerHTML = `<tr><td colspan="5" class="error">Error: ${err.message}</td></tr>`
84
+ }
85
+ }
86
+
87
+ document.getElementById('refresh-pages-btn').addEventListener('click', loadPages)
88
+ loadPages()
89
+
90
+ async function showPageDetail(id) {
91
+ try {
92
+ const res = await fetch(`/pages/${id}`)
93
+ const page = await res.json()
94
+
95
+ const modal = document.getElementById('page-detail')
96
+ modal.innerHTML = `
97
+ <button class="close-btn" onclick="closeModal()">&times;</button>
98
+ <h3>${page.url}</h3>
99
+ <p><strong>Title:</strong> ${page.title || 'N/A'}</p>
100
+ <p><strong>Status:</strong> ${page.error || 'Success'}</p>
101
+ ${page.prediction ? `
102
+ <p><strong>Category:</strong> <span class="category ${page.prediction.category}">${page.prediction.category}</span></p>
103
+ <p><strong>Confidence:</strong> ${(page.prediction.confidence * 100).toFixed(1)}%</p>
104
+ ` : ''}
105
+ ${page.features ? `
106
+ <h4>Features:</h4>
107
+ <pre>${JSON.stringify(page.features, null, 2)}</pre>
108
+ ` : ''}
109
+ `
110
+ modal.classList.remove('hidden')
111
+ } catch (err) {
112
+ alert('Error loading page details')
113
+ }
114
+ }
115
+
116
+ window.showPageDetail = showPageDetail
117
+
118
+ function closeModal() {
119
+ document.getElementById('page-detail').classList.add('hidden')
120
+ }
121
+
122
+ window.closeModal = closeModal
123
+
124
+ document.getElementById('retrain-btn').addEventListener('click', async () => {
125
+ const result = document.getElementById('model-result')
126
+ result.textContent = 'Retraining...'
127
+
128
+ try {
129
+ const res = await fetch('/model/retrain', { method: 'POST' })
130
+ const data = await res.json()
131
+ result.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`
132
+ } catch (err) {
133
+ result.innerHTML = `<p class="error">Error: ${err.message}</p>`
134
+ }
135
+ })
136
+
137
+ document.getElementById('vacuum-btn').addEventListener('click', async () => {
138
+ const result = document.getElementById('model-result')
139
+ result.textContent = 'Vacuuming...'
140
+
141
+ try {
142
+ const res = await fetch('/db/vacuum', { method: 'POST' })
143
+ const data = await res.json()
144
+ result.innerHTML = `<p class="success">${data.status}</p>`
145
+ } catch (err) {
146
+ result.innerHTML = `<p class="error">Error: ${err.message}</p>`
147
+ }
148
+ })
149
+
150
+ document.getElementById('predict-form').addEventListener('submit', async (e) => {
151
+ e.preventDefault()
152
+ const html = document.getElementById('html-content').value
153
+ const title = document.getElementById('predict-title').value
154
+
155
+ if (!html) return
156
+
157
+ const result = document.getElementById('predict-result')
158
+ result.textContent = 'Classifying...'
159
+
160
+ try {
161
+ const res = await fetch('/model/predict', {
162
+ method: 'POST',
163
+ headers: { 'Content-Type': 'application/json' },
164
+ body: JSON.stringify({ html, title })
165
+ })
166
+ const data = await res.json()
167
+ result.innerHTML = `
168
+ <p><strong>Category:</strong> <span class="category ${data.prediction.category}">${data.prediction.category}</span></p>
169
+ <p><strong>Confidence:</strong> ${(data.prediction.confidence * 100).toFixed(1)}%</p>
170
+ <p><strong>Relevance:</strong> ${(data.prediction.relevance_score * 100).toFixed(1)}%</p>
171
+ `
172
+ } catch (err) {
173
+ result.innerHTML = `<p class="error">Error: ${err.message}</p>`
174
+ }
175
+ })
176
+
177
+ async function loadStats() {
178
+ const container = document.getElementById('stats-content')
179
+
180
+ try {
181
+ const res = await fetch('/stats')
182
+ const stats = await res.json()
183
+
184
+ container.innerHTML = `
185
+ <div class="stat-card"><div class="value">${stats.total_pages}</div><div class="label">Total Pages</div></div>
186
+ <div class="stat-card"><div class="value">${stats.success_pages}</div><div class="label">Successful</div></div>
187
+ <div class="stat-card"><div class="value">${stats.error_pages}</div><div class="label">Errors</div></div>
188
+ <div class="stat-card"><div class="value">${stats.total_predictions}</div><div class="label">Predictions</div></div>
189
+ <div class="stat-card"><div class="value">${stats.database_size_mb}</div><div class="label">DB Size (MB)</div></div>
190
+ `
191
+ } catch (err) {
192
+ container.innerHTML = `<p class="error">Error loading stats</p>`
193
+ }
194
+ }
195
+
196
+ loadStats()
197
+
198
+ window.truncate = (str, len) => str.length > len ? str.slice(0, len) + '...' : str
199
+ })
static/index.html ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Web Scraper</title>
7
+ <link rel="stylesheet" href="/static/style.css">
8
+ </head>
9
+ <body>
10
+ <header>
11
+ <h1>Web Scraper</h1>
12
+ <p>ML-based content classification</p>
13
+ </header>
14
+
15
+ <nav class="tabs">
16
+ <button class="tab-btn active" data-tab="scrape">Scrape</button>
17
+ <button class="tab-btn" data-tab="jobs">Jobs</button>
18
+ <button class="tab-btn" data-tab="pages">Pages</button>
19
+ <button class="tab-btn" data-tab="stats">Stats</button>
20
+ <button class="tab-btn" data-tab="model">Model</button>
21
+ </nav>
22
+
23
+ <main>
24
+ <section id="scrape" class="tab-content active">
25
+ <h2>Submit Scraping Job</h2>
26
+ <form id="scrape-form">
27
+ <label for="urls">URLs (one per line):</label>
28
+ <textarea id="urls" rows="5" placeholder="https://example.com&#10;https://news.ycombinator.com"></textarea>
29
+ <button type="submit">Start Scraping</button>
30
+ </form>
31
+ <div id="scrape-result" class="result"></div>
32
+ </section>
33
+
34
+ <section id="jobs" class="tab-content">
35
+ <h2>Job Status</h2>
36
+ <div class="form-row">
37
+ <input type="text" id="job-id-input" placeholder="Enter Job ID">
38
+ <button id="check-job-btn">Check Status</button>
39
+ </div>
40
+ <div id="job-result" class="result"></div>
41
+ </section>
42
+
43
+ <section id="pages" class="tab-content">
44
+ <h2>Scraped Pages</h2>
45
+ <div class="filters">
46
+ <select id="status-filter">
47
+ <option value="">All Pages</option>
48
+ <option value="success">Successful</option>
49
+ <option value="error">Errors</option>
50
+ </select>
51
+ <button id="refresh-pages-btn">Refresh</button>
52
+ </div>
53
+ <table id="pages-table">
54
+ <thead>
55
+ <tr>
56
+ <th>ID</th>
57
+ <th>URL</th>
58
+ <th>Title</th>
59
+ <th>Category</th>
60
+ <th>Status</th>
61
+ </tr>
62
+ </thead>
63
+ <tbody></tbody>
64
+ </table>
65
+ <div id="page-detail" class="modal hidden"></div>
66
+ </section>
67
+
68
+ <section id="stats" class="tab-content">
69
+ <h2>Statistics</h2>
70
+ <div id="stats-content" class="stats-grid"></div>
71
+ </section>
72
+
73
+ <section id="model" class="tab-content">
74
+ <h2>ML Model</h2>
75
+ <div class="model-actions">
76
+ <button id="retrain-btn">Retrain Model</button>
77
+ <button id="vacuum-btn">Vacuum Database</button>
78
+ </div>
79
+ <div id="model-result" class="result"></div>
80
+
81
+ <h3>Predict Content</h3>
82
+ <form id="predict-form">
83
+ <textarea id="html-content" rows="5" placeholder="<html>...</html>"></textarea>
84
+ <input type="text" id="predict-title" placeholder="Title (optional)">
85
+ <button type="submit">Classify</button>
86
+ </form>
87
+ <div id="predict-result" class="result"></div>
88
+ </section>
89
+ </main>
90
+
91
+ <script src="/static/app.js"></script>
92
+ </body>
93
+ </html>
static/style.css ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ * {
2
+ box-sizing: border-box;
3
+ margin: 0;
4
+ padding: 0;
5
+ }
6
+
7
+ body {
8
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
9
+ background: #0f0f23;
10
+ color: #e4e4ef;
11
+ min-height: 100vh;
12
+ line-height: 1.6;
13
+ }
14
+
15
+ header {
16
+ text-align: center;
17
+ padding: 2rem 1rem;
18
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
19
+ }
20
+
21
+ header h1 {
22
+ font-size: 2.5rem;
23
+ }
24
+
25
+ header p {
26
+ opacity: 0.8;
27
+ }
28
+
29
+ nav.tabs {
30
+ display: flex;
31
+ justify-content: center;
32
+ gap: 0.5rem;
33
+ padding: 1rem;
34
+ background: #1a1a2e;
35
+ flex-wrap: wrap;
36
+ }
37
+
38
+ .tab-btn {
39
+ padding: 0.75rem 1.5rem;
40
+ background: #16213e;
41
+ color: #e4e4ef;
42
+ border: 1px solid #333;
43
+ cursor: pointer;
44
+ border-radius: 4px;
45
+ transition: all 0.2s;
46
+ }
47
+
48
+ .tab-btn:hover {
49
+ background: #667eea;
50
+ }
51
+
52
+ .tab-btn.active {
53
+ background: #667eea;
54
+ border-color: #667eea;
55
+ }
56
+
57
+ main {
58
+ max-width: 1000px;
59
+ margin: 0 auto;
60
+ padding: 2rem 1rem;
61
+ }
62
+
63
+ .tab-content {
64
+ display: none;
65
+ }
66
+
67
+ .tab-content.active {
68
+ display: block;
69
+ }
70
+
71
+ h2 {
72
+ margin-bottom: 1rem;
73
+ color: #667eea;
74
+ }
75
+
76
+ form, .form-row {
77
+ display: flex;
78
+ flex-direction: column;
79
+ gap: 1rem;
80
+ margin-bottom: 1rem;
81
+ }
82
+
83
+ .form-row {
84
+ flex-direction: row;
85
+ }
86
+
87
+ .form-row input {
88
+ flex: 1;
89
+ }
90
+
91
+ textarea, input, select, button {
92
+ padding: 0.75rem;
93
+ background: #16213e;
94
+ border: 1px solid #333;
95
+ color: #e4e4ef;
96
+ border-radius: 4px;
97
+ font: inherit;
98
+ }
99
+
100
+ textarea {
101
+ resize: vertical;
102
+ min-height: 100px;
103
+ }
104
+
105
+ button {
106
+ background: #667eea;
107
+ color: white;
108
+ cursor: pointer;
109
+ border: none;
110
+ font-weight: 500;
111
+ transition: background 0.2s;
112
+ }
113
+
114
+ button:hover {
115
+ background: #5568d3;
116
+ }
117
+
118
+ button:disabled {
119
+ opacity: 0.5;
120
+ cursor: not-allowed;
121
+ }
122
+
123
+ .result {
124
+ background: #16213e;
125
+ padding: 1rem;
126
+ border-radius: 4px;
127
+ margin-top: 1rem;
128
+ white-space: pre-wrap;
129
+ word-break: break-all;
130
+ }
131
+
132
+ .filters {
133
+ display: flex;
134
+ gap: 0.5rem;
135
+ margin-bottom: 1rem;
136
+ }
137
+
138
+ .filters select {
139
+ flex: 1;
140
+ max-width: 200px;
141
+ }
142
+
143
+ table {
144
+ width: 100%;
145
+ border-collapse: collapse;
146
+ background: #16213e;
147
+ border-radius: 4px;
148
+ overflow: hidden;
149
+ }
150
+
151
+ th, td {
152
+ padding: 0.75rem;
153
+ text-align: left;
154
+ border-bottom: 1px solid #333;
155
+ }
156
+
157
+ th {
158
+ background: #1a1a2e;
159
+ font-weight: 500;
160
+ }
161
+
162
+ tr:hover {
163
+ background: #1a1a2e;
164
+ }
165
+
166
+ .category {
167
+ display: inline-block;
168
+ padding: 0.25rem 0.5rem;
169
+ border-radius: 3px;
170
+ font-size: 0.85rem;
171
+ }
172
+
173
+ .category.news { background: #3498db; }
174
+ .category.blog { background: #2ecc71; }
175
+ .category.product { background: #e74c3c; }
176
+ .category.documentation { background: #9b59b6; }
177
+ .category.forum { background: #f39c12; }
178
+ .category.social { background: #1abc9c; }
179
+ .category.landing { background: #e67e22; }
180
+ .category.ecommerce { background: #c0392b; }
181
+ .category.article { background: #16a085; }
182
+ .category.other { background: #7f8c8d; }
183
+
184
+ .stats-grid {
185
+ display: grid;
186
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
187
+ gap: 1rem;
188
+ }
189
+
190
+ .stat-card {
191
+ background: #16213e;
192
+ padding: 1.5rem;
193
+ border-radius: 8px;
194
+ text-align: center;
195
+ }
196
+
197
+ .stat-card .value {
198
+ font-size: 2rem;
199
+ font-weight: bold;
200
+ color: #667eea;
201
+ }
202
+
203
+ .stat-card .label {
204
+ font-size: 0.9rem;
205
+ opacity: 0.7;
206
+ }
207
+
208
+ .modal {
209
+ position: fixed;
210
+ top: 50%;
211
+ left: 50%;
212
+ transform: translate(-50%, -50%);
213
+ background: #16213e;
214
+ padding: 2rem;
215
+ border-radius: 8px;
216
+ max-width: 800px;
217
+ max-height: 80vh;
218
+ overflow: auto;
219
+ z-index: 100;
220
+ border: 1px solid #333;
221
+ }
222
+
223
+ .modal.hidden {
224
+ display: none;
225
+ }
226
+
227
+ .overlay {
228
+ position: fixed;
229
+ top: 0;
230
+ left: 0;
231
+ right: 0;
232
+ bottom: 0;
233
+ background: rgba(0,0,0,0.7);
234
+ z-index: 50;
235
+ }
236
+
237
+ .close-btn {
238
+ position: absolute;
239
+ top: 0.5rem;
240
+ right: 0.5rem;
241
+ background: transparent;
242
+ border: none;
243
+ font-size: 1.5rem;
244
+ cursor: pointer;
245
+ color: #e4e4ef;
246
+ }
247
+
248
+ .model-actions {
249
+ display: flex;
250
+ gap: 1rem;
251
+ margin-bottom: 1rem;
252
+ }
253
+
254
+ .error {
255
+ color: #e74c3c;
256
+ }
257
+
258
+ .success {
259
+ color: #2ecc71;
260
+ }