Spaces:
Sleeping
Sleeping
File size: 13,781 Bytes
742f3fd | 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 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | from pathlib import Path
# Clean BOM
for path in Path("app").rglob("*.py"):
text = path.read_text(encoding="utf-8-sig")
text = text.replace("\ufeff", "")
path.write_text(text, encoding="utf-8")
hf_path = Path("app/deployment/hf_status.py")
text = hf_path.read_text(encoding="utf-8-sig")
text = text.replace("\ufeff", "")
append_code = r'''
# =====================================================
# Phase 34 override: professional answer rendering
# =====================================================
try:
_phase34_previous_get_product_app_html = get_product_app_html
except NameError:
_phase34_previous_get_product_app_html = None
def get_product_app_html() -> str:
if _phase34_previous_get_product_app_html is None:
return "<h1>GraphResearcher App</h1><p>App UI is unavailable.</p>"
html = _phase34_previous_get_product_app_html()
css = """
<style>
.answer-card {
line-height: 1.72;
}
.answer-card h2 {
margin: 0 0 10px;
font-size: 18px;
color: #0f172a;
}
.answer-card h3 {
margin: 18px 0 8px;
font-size: 15px;
color: #1d4ed8;
}
.answer-card p {
margin: 8px 0;
}
.answer-card ol,
.answer-card ul {
padding-left: 22px;
margin: 8px 0;
}
.answer-card li {
margin-bottom: 8px;
}
.evidence-box {
background: #f8fafc;
border: 1px solid #e5e7eb;
border-radius: 12px;
padding: 11px;
margin-top: 9px;
font-size: 13px;
color: #475569;
}
.source-chip {
display: inline-block;
background: #eef2ff;
color: #3730a3;
padding: 3px 7px;
border-radius: 999px;
font-size: 12px;
margin: 2px;
font-weight: 700;
}
.answer-warning {
background: #fff7ed;
border: 1px solid #fed7aa;
color: #9a3412;
padding: 10px;
border-radius: 12px;
margin: 10px 0;
}
</style>
"""
if "answer-card" not in html:
html = html.replace("</head>", css + "\n</head>")
js = """
<script>
/*
Phase 34:
Render answers like a real ChatGPT-style app.
The backend may return plain text, but the UI now converts it into:
Direct answer, structured points, evidence, and source grounding.
*/
function htmlEscapePhase34(value) {
return String(value || '')
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('\"', '"');
}
function stripHtmlPhase34(value) {
const div = document.createElement('div');
div.innerHTML = value || '';
return div.textContent || div.innerText || '';
}
function answerLooksWeakPhase34(answer) {
const text = String(answer || '').trim();
const words = text.split(/\\s+/).filter(Boolean);
if (words.length < 110) return true;
if (text.toLowerCase().includes('i could not find relevant indexed sources')) return true;
if (!text.includes('\\n') && words.length < 170) return true;
return false;
}
function splitIntoPointsPhase34(text) {
const cleaned = String(text || '')
.replace(/\\s+/g, ' ')
.trim();
if (!cleaned) return [];
const numbered = cleaned.split(/(?=\\b\\d+\\.\\s+)/).map(x => x.trim()).filter(Boolean);
if (numbered.length >= 2) {
return numbered;
}
return cleaned
.split(/(?<=[.!?])\\s+/)
.map(x => x.trim())
.filter(x => x.length > 20)
.slice(0, 8);
}
function renderPlainAnswerPhase34(answer) {
const escaped = htmlEscapePhase34(answer);
let html = escaped;
html = html.replace(/\\*\\*(.*?)\\*\\*/g, '<b>$1</b>');
const lines = html.split('\\n').map(x => x.trim()).filter(Boolean);
if (lines.length <= 1) {
return '<p>' + html + '</p>';
}
let out = '';
lines.forEach(line => {
if (/^\\d+\\.\\s+/.test(line)) {
out += '<li>' + line.replace(/^\\d+\\.\\s+/, '') + '</li>';
} else if (/^[-*]\\s+/.test(line)) {
out += '<li>' + line.replace(/^[-*]\\s+/, '') + '</li>';
} else {
out += '<p>' + line + '</p>';
}
});
if (out.includes('<li>')) {
out = '<ol>' + out + '</ol>';
}
return out;
}
function buildSourceGroundingPhase34(data, doc) {
let sources = [];
try {
sources = buildSources(data, doc).slice(0, 5);
} catch (error) {
sources = [];
}
if (!sources.length) {
return {
html: '<div class=\"answer-warning\">No source metadata was returned with this answer. If this document was uploaded before a Hugging Face rebuild, clear cache and re-upload it.</div>',
sources: []
};
}
let html = '';
sources.forEach((source, index) => {
const label = htmlEscapePhase34(source.source_id || ('S' + (index + 1)));
const page = htmlEscapePhase34(source.page || 'Not available');
const chunk = htmlEscapePhase34(source.chunk_id || 'Not available');
const preview = htmlEscapePhase34(String(source.preview || '').slice(0, 320));
html += `
<div class="evidence-box">
<b>[${label}]</b>
<span class="source-chip">Page: ${page}</span>
<span class="source-chip">Chunk: ${chunk}</span>
<div style="margin-top:6px;">${preview}</div>
</div>
`;
});
return { html, sources };
}
function formatProfessionalAnswerPhase34(question, data, doc) {
const rawAnswer = String(data.answer || 'I could not generate an answer.').trim();
const grounding = buildSourceGroundingPhase34(data, doc);
const weak = answerLooksWeakPhase34(rawAnswer);
const questionLower = String(question || '').toLowerCase();
const wantsSteps =
questionLower.includes('step') ||
questionLower.includes('sequential') ||
questionLower.includes('build') ||
questionLower.includes('procedure') ||
questionLower.includes('starting point');
let html = '<div class="answer-card">';
if (rawAnswer.toLowerCase().includes('i could not find relevant indexed sources')) {
html += '<h2>I could not find indexed evidence for this question</h2>';
html += '<div class="answer-warning">This usually means the browser still remembers an old document, but the Hugging Face backend lost its uploaded/indexed files after rebuild. Use Clear Workspace Cache, re-upload the document, then ask again.</div>';
html += '</div>';
return html;
}
if (wantsSteps) {
html += '<h2>Step-by-step answer</h2>';
} else {
html += '<h2>Answer</h2>';
}
if (weak) {
const points = splitIntoPointsPhase34(rawAnswer);
html += '<h3>Direct answer</h3>';
html += '<p>' + htmlEscapePhase34(points[0] || rawAnswer) + '</p>';
if (points.length > 1) {
html += '<h3>Detailed points</h3><ol>';
points.slice(0, 8).forEach(point => {
let cleaned = point.replace(/^\\d+\\.\\s+/, '');
html += '<li>' + htmlEscapePhase34(cleaned) + '</li>';
});
html += '</ol>';
}
html += '<h3>Evidence used from the document</h3>';
html += grounding.html;
html += '<h3>How to verify</h3>';
html += '<p>Use the source cards on the right. Each source shows the document name, page number, chunk ID, and an Open source button.</p>';
} else {
html += renderPlainAnswerPhase34(rawAnswer);
html += '<h3>Evidence used from the document</h3>';
html += grounding.html;
}
html += '</div>';
return html;
}
function renderMessages() {
const box = document.getElementById('messages');
const doc = getSelectedDocument();
const compareDoc = getCompareDocument ? getCompareDocument() : null;
if (!doc) {
box.innerHTML = `
<div class="empty">
<h1>Upload a document to start</h1>
<p>No document ID needed. Upload a file from the left sidebar, then chat normally.</p>
</div>
`;
return;
}
const convo = getConversation();
if (convo.length === 0) {
box.innerHTML = `
<div class="empty">
<h1>${compareDoc ? 'Compare documents' : 'Chat with your document'}</h1>
<p>
${compareDoc
? `You are comparing ${htmlEscapePhase34(doc.name)} with ${htmlEscapePhase34(compareDoc.name)}. Ask a comparison question below.`
: `Ask a question about ${htmlEscapePhase34(doc.name)}. Answers will include source-backed evidence.`}
</p>
</div>
`;
return;
}
box.innerHTML = '';
convo.forEach(msg => {
const wrapper = document.createElement('div');
wrapper.className = 'message ' + msg.role;
if (msg.type === 'compare') {
const bubble = document.createElement('div');
bubble.className = 'compare-bubble';
bubble.innerHTML = `
<h2>Comparison Answer</h2>
<p><b>Question:</b> ${htmlEscapePhase34(msg.question)}</p>
<div class="compare-grid">
<div class="compare-card">
<h3>${htmlEscapePhase34(msg.docAName)}</h3>
${msg.answerAHtml || htmlEscapePhase34(msg.answerA)}
</div>
<div class="compare-card">
<h3>${htmlEscapePhase34(msg.docBName)}</h3>
${msg.answerBHtml || htmlEscapePhase34(msg.answerB)}
</div>
</div>
`;
wrapper.appendChild(bubble);
} else {
const bubble = document.createElement('div');
bubble.className = 'bubble';
if (msg.role === 'assistant' && msg.html) {
bubble.innerHTML = msg.html;
} else {
bubble.textContent = msg.content || '';
}
wrapper.appendChild(bubble);
}
box.appendChild(wrapper);
});
box.scrollTop = box.scrollHeight;
}
async function sendMessage() {
const doc = getSelectedDocument();
const compareDoc = getCompareDocument ? getCompareDocument() : null;
const input = document.getElementById('messageInput');
const userText = input.value.trim();
if (!doc) {
alert('Upload or select a document first.');
return;
}
if (!userText) return;
const convo = getConversation();
convo.push({
role: 'user',
content: userText,
createdAt: new Date().toISOString()
});
input.value = '';
saveConversations();
renderMessages();
setStatus(compareDoc ? 'Comparing...' : 'Thinking...');
document.getElementById('metricsBox').innerHTML = '';
try {
if (compareDoc) {
const dataA = await callAsk(askPayload(buildContextualQuery(userText, true), doc.id));
const dataB = await callAsk(askPayload(buildContextualQuery(userText, true), compareDoc.id));
const answerAHtml = formatProfessionalAnswerPhase34(userText, dataA, doc);
const answerBHtml = formatProfessionalAnswerPhase34(userText, dataB, compareDoc);
convo.push({
role: 'assistant',
type: 'compare',
question: userText,
docAName: doc.name || 'Document A',
docBName: compareDoc.name || 'Document B',
answerA: dataA.answer || 'No answer from first document.',
answerB: dataB.answer || 'No answer from second document.',
answerAHtml,
answerBHtml,
rawA: dataA,
rawB: dataB,
createdAt: new Date().toISOString()
});
saveConversations();
renderMessages();
updateMetrics(dataA, doc.name || 'Document A');
updateMetrics(dataB, compareDoc.name || 'Document B');
updateCitations([
{ label: doc.name || 'Document A', sources: buildSources(dataA, doc) },
{ label: compareDoc.name || 'Document B', sources: buildSources(dataB, compareDoc) }
]);
setStatus('Comparison ready');
} else {
const data = await callAsk(askPayload(buildContextualQuery(userText), doc.id));
const answer = data.answer || 'I could not generate an answer.';
const html = formatProfessionalAnswerPhase34(userText, data, doc);
convo.push({
role: 'assistant',
content: stripHtmlPhase34(html),
html,
createdAt: new Date().toISOString(),
raw: data
});
saveConversations();
renderMessages();
updateMetrics(data, doc.name || 'Selected document');
updateCitations([
{ label: doc.name || 'Selected document', sources: buildSources(data, doc) }
]);
setStatus('Ready');
}
} catch (error) {
convo.push({
role: 'assistant',
content: 'Error: ' + error.message,
createdAt: new Date().toISOString()
});
saveConversations();
renderMessages();
setStatus('Error');
}
}
</script>
"""
if "Phase 34:" not in html:
html = html.replace("</body>", js + "\n</body>")
return html
'''
if "Phase 34 override: professional answer rendering" not in text:
text += "\n\n" + append_code
print("Phase 34 professional answer renderer added.")
else:
print("Phase 34 already exists.")
hf_path.write_text(text, encoding="utf-8")
print("Done.")
|