File size: 17,397 Bytes
60d3c71 | 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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enhanced FactGPT</title>
</head>
<body>
<div id="searchbox">
<div id="backsearch">
<!-- React will render search bar & button here -->
</div>
<!-- THINKING + ANSWER WINDOWS (hidden by default) -->
<div id="ask" class="hidden">
<div id="thinking"></div>
<div id="chat"></div>
</div>
<!-- DOCUMENT RESULTS -->
<div id="documents"></div>
</div>
<div class="graph" id="graph"></div>
<!-- React & ReactDOM -->
<script src="https://cdn.jsdelivr.net/npm/react@18.0.0/umd/react.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/react-dom@18.0.0/umd/react-dom.production.min.js"></script>
<!-- Babel for in-browser JSX transform -->
<script src="https://cdn.jsdelivr.net/npm/babel-standalone@6.26.0/babel.min.js"></script>
<!-- Three.js -->
<script src="https://cdn.jsdelivr.net/npm/three@0.160.1/build/three.min.js"></script>
<!-- three-spritetext -->
<script src="https://cdn.jsdelivr.net/npm/three-spritetext@1.9.3/dist/three-spritetext.min.js"></script>
<!-- react-force-graph-3d -->
<script src="https://cdn.jsdelivr.net/npm/react-force-graph-3d@1.25.1/dist/react-force-graph-3d.min.js"></script>
<script type="text/jsx">
const { useRef } = React;
/* ----------------------------- */
/* SEARCH + INTERACTION COMPONENT */
/* ----------------------------- */
class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
query: "",
node: null,
k: 40
};
this.timer = null;
this.handleChangeText = this.handleChangeText.bind(this);
this.handleHoverNode = this.handleHoverNode.bind(this);
this.handleClickTag = this.handleClickTag.bind(this);
this.search = this.search.bind(this);
this.plot = this.plot.bind(this);
this.highlight = this.highlight.bind(this);
this.handleClickDate = this.handleClickDate.bind(this);
this.chat = this.chat.bind(this);
// Get query and node from URL – same behaviour as before
const params = new URLSearchParams(window.location.search);
const query = params.get("query") || "";
const node = params.get("node") || null;
if (query.length > 0) {
this.state.query = query;
this.handlePlot(query, this.state.k, false);
if (node !== null) {
this.state.node = node;
this.search(query + " " + node, this.state.k);
}
}
}
/* --------------- UTILITIES --------------- */
handlePlot = (query, k, timer = true) => {
this.search(query, k);
clearTimeout(this.timer);
if (timer) {
this.timer = setTimeout(() => {
this.plot(query, k);
}, 600);
} else {
this.plot(query, k);
}
};
/* Deduplicate + filter filler text */
cleanFiller(text) {
if (!text) return "";
// Remove repeated "Okay, let's see" (case‑insensitive)
return text.replace(/(?:Okay,\s?let'?s\s?see[\.\s]*)+/gi, "").trim();
}
formatText(text) {
if (!text) return '';
const cleaned = this.cleanFiller(text);
return cleaned
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*?)\*/g, '<em>$1</em>')
.replace(/`(.*?)`/g, '<code style="background-color: rgba(25,188,142,0.2); padding: 2px 4px; border-radius: 3px;">$1</code>')
.replace(/\n/g, '<br>');
}
handleChangeText(event) {
const value = event.target.value.toLowerCase();
this.setState({ query: value, node: null });
window.history.pushState({}, null, `?query=${encodeURIComponent(value)}`);
document.getElementById('ask').classList.add('hidden'); // hide thinking/answer until Ask
if (value.trim().length > 0) {
this.handlePlot(value, this.state.k);
}
}
handleHoverNode(node) {
if (node !== null) {
this.setState({ node: node.id });
this.search(this.state.query + " " + node.id, this.state.k);
window.history.pushState({}, null, `?query=${encodeURIComponent(this.state.query)}&node=${encodeURIComponent(node.id)}`);
}
}
highlight(text) {
if (this.state.query.length > 1) {
let keywords = this.state.query;
if (this.state.node !== null) {
keywords = keywords + " " + this.state.node;
}
keywords = keywords.split(/\s/).filter(token => token.length > 2);
const setKeywords = new Set(keywords);
const parts = text.split(new RegExp(`(${keywords.join("|")})`, 'gi'));
return <div id="inline">{parts.map((part, index) =>
setKeywords.has(part.toLowerCase()) ?
<div key={index} id="highlight">{part}</div> : part
)}</div>;
} else {
return <div id="inline">{text}</div>;
}
}
handleClickDate() {
this.search(this.state.query, this.state.k, true);
}
handleClickTag(tag) {
const query = `${this.state.query} ${tag}`;
this.setState({ query });
document.getElementById("search").value = query;
this.handlePlot(query, this.state.k);
}
/* -------------------- CHAT -------------------- */
chat() {
// show thinking + answer pane
const askEl = document.getElementById('ask');
askEl.classList.remove('hidden');
const thinkingEl = document.getElementById('thinking');
const chatEl = document.getElementById('chat');
// Reset panes
thinkingEl.innerHTML = '';
thinkingEl.style.display = 'block';
chatEl.innerHTML = '';
chatEl.style.display = 'none';
let fullText = '';
const decoder = new TextDecoder();
const query = encodeURIComponent(
this.state.query + (this.state.node ? ' ' + this.state.node : '')
);
thinkingEl.innerHTML = 'Processing your query<span class="loading-dots"></span>';
fetch(`/chat/20/${query}`)
.then(response => {
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return response.body.getReader();
})
.then(reader => {
const processStream = ({ done, value }) => {
if (done) {
const thinkingMatch = fullText.match(/<think>([\s\S]*?)<\/think>/);
if (thinkingMatch) {
const thinkingContent = thinkingMatch[1].trim();
const finalAnswer = fullText.replace(/<think>[\s\S]*?<\/think>/, '').trim();
thinkingEl.innerHTML = this.formatText(thinkingContent);
chatEl.innerHTML = this.formatText(finalAnswer);
} else {
thinkingEl.style.display = 'none';
chatEl.innerHTML = this.formatText(fullText);
}
chatEl.style.display = 'block';
chatEl.scrollTop = 0;
return;
}
const chunk = decoder.decode(value, { stream: true });
if (chunk.length > fullText.length) {
fullText = chunk;
} else {
fullText = chunk;
}
if (fullText.includes('<think>') && !fullText.includes('</think>')) {
const thinkStart = fullText.indexOf('<think>') + 7;
const currentThinking = fullText.slice(thinkStart);
thinkingEl.innerHTML = this.formatText(currentThinking) + '<span class="loading-dots"></span>';
thinkingEl.scrollTop = thinkingEl.scrollHeight;
} else if (fullText.includes('</think>')) {
const thinkingMatch = fullText.match(/<think>([\s\S]*?)<\/think>/);
if (thinkingMatch) {
const thinkingContent = thinkingMatch[1].trim();
const afterThinking = fullText.substring(fullText.indexOf('</think>') + 8);
thinkingEl.innerHTML = this.formatText(thinkingContent);
chatEl.style.display = 'block';
if (afterThinking.trim()) {
chatEl.innerHTML = this.formatText(afterThinking) + '<span class="loading-dots"></span>';
} else {
chatEl.innerHTML = 'Preparing final answer<span class="loading-dots"></span>';
}
chatEl.scrollTop = chatEl.scrollHeight;
}
} else if (fullText.trim() && !fullText.includes('<think>')) {
thinkingEl.style.display = 'none';
chatEl.style.display = 'block';
chatEl.innerHTML = this.formatText(fullText) + '<span class="loading-dots"></span>';
chatEl.scrollTop = chatEl.scrollHeight;
}
return reader.read().then(processStream);
};
return reader.read().then(processStream);
})
.catch(err => {
console.error('Chat error:', err);
thinkingEl.style.display = 'none';
chatEl.style.display = 'block';
chatEl.innerHTML = `<div style="color: #ff6b6b;">❌ Connection error. Please check if the server is running on localhost:8080</div>`;
});
// Update document viewer simultaneously
this.search(this.state.query, this.state.k, false, false);
}
/* -------------------- SEARCH + PLOT -------------------- */
search(query, k, sort = false, hide = true) {
fetch(`/search/${sort}/${this.state.node || 'null'}/${k}/${query.replace('/', '')}`)
.then(res => res.json())
.then(data => {
ReactDOM.render(
<div>
{Object.entries(data["documents"]).map((document, index) =>
<div key={index} id="document">
<a className="title" href={document[1]["url"]} target="_blank">
{index + 1}. {this.highlight(document[1]["title"]) }
</a>
<div id="date" onClick={() => this.handleClickDate()}>
{this.highlight(document[1]["date"]) }
</div>
<div id="summary">{this.highlight(document[1]["summary"]) }</div>
<div id="tags">
{document[1]["tags"].concat(document[1]["extra-tags"]).map((tag, tagIndex) =>
<div key={tagIndex} id="tag" onClick={() => this.handleClickTag(tag)}>
{this.highlight(tag)}
</div>
)}
</div>
</div>
)}
</div>,
document.getElementById('documents')
);
})
.catch(err => console.error('Search error:', err));
}
plot(query, k) {
fetch(`/plot/${k}/${query.replace('/', '')}`)
.then(res => res.json())
.then(data => {
ReactDOM.render(
<ForceGraph3D
graphData={data}
backgroundColor="#131317"
width={window.innerWidth / 2}
height={window.innerHeight}
showNavInfo={false}
nodeAutoColorBy="group"
linkOpacity={0.6}
linkWidth={0.1}
linkResolution={10}
linkDirectionalParticleColor={() => "#FFFFFF"}
linkDirectionalParticles={1}
linkDirectionalParticleWidth={0.2}
linkDirectionalParticleResolution={8}
linkColor="#FFFFFF"
linkThreeObjectExtend={true}
linkThreeObject={link => {
const sprite = new SpriteText(`${link.relation}`);
sprite.color = '#FFFFFF';
sprite.textHeight = 2;
sprite.fontSize = 0;
sprite.fontFace = "Futura";
return sprite;
}}
linkPositionUpdate={(sprite, { start, end }) => {
const middlePos = Object.assign(...['x', 'y', 'z'].map(c => ({
[c]: start[c] + (end[c] - start[c]) / 2
})));
Object.assign(sprite.position, middlePos);
}}
nodeThreeObject={node => {
const sprite = new SpriteText(node.id);
sprite.color = node.color;
sprite.textHeight = 4;
sprite.fontSize = 50;
sprite.fontFace = "Futura";
return sprite;
}}
onNodeHover={node => { this.handleHoverNode(node); }}
/>,
document.getElementById('graph')
);
})
.catch(err => console.error('Plot error:', err));
}
/* -------------------- RENDER -------------------- */
render() {
return (
<React.Fragment>
<input
id="search"
type="text"
placeholder="Neural Search"
value={this.state.query}
onChange={this.handleChangeText}
autoFocus
/>
<button className="ask" role="button" onClick={this.chat}>Ask</button>
</React.Fragment>
);
}
}
/* Mount React */
ReactDOM.createRoot(document.getElementById('backsearch')).render(<Search />);
</script>
<link rel="stylesheet" href="style.css">
</body>
</html>
|