Spaces:
Sleeping
Sleeping
D Ф m i И i q ц e L Ф y e r commited on
Commit ·
f816411
1
Parent(s): 5985437
Add backend toggle with auto-detect for HF Space environment
Browse files16 unmodified lines1718192021222395 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421436 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721731741751761771785 unmodified lines1841851861871881891901911921931941951961971981992002012022032042052069 unmodified lines2162172182192202212222232242252262272282292302312323 unmodified lines2362372382392402412422432442452462472482492502512522532542552565 unmodified lines2622632642652662672682692702712723 unmodified lines2762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373386 unmodified lines34534634734834935035135235335435535618 unmodified lines3753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084093 unmodified lines4134144154164174184194204214224234244252 unmodified lines42842943043143243343443543643743843944044144244344444544644744844912 unmodified lines46246346446546646746846947047147247347447547647747811 unmodified lines49049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885916 unmodified linesborder: 1px solid rgba(255, 255, 255, 0.1);position: relative;display: block;/* Force display */}* {95 unmodified linestransform: none;}.results {display: none;}.results.visible {display: block;animation: fadeIn 0.5s ease;}@keyframes fadeIn {from {opacity: 0;transform: translateY(20px);}to {opacity: 1;transform: translateY(0);}}.score-card {6 unmodified linesmargin-bottom: 2rem;}.score-value {font-size: 4rem;font-weight: 700;margin: 1rem 0;}.score-high {color: #22c55e;}.score-medium {color: #eab308;}.score-low {color: #ef4444;}.score-label {font-size: 1.2rem;color: #8b8ba7;margin-bottom: 1rem;}.credibility-badge {display: inline-block;5 unmodified linesletter-spacing: 1px;}.badge-high {background: rgba(34, 197, 94, 0.2);color: #22c55e;border: 1px solid #22c55e;}.badge-medium {background: rgba(234, 179, 8, 0.2);color: #eab308;border: 1px solid #eab308;}.badge-low {background: rgba(239, 68, 68, 0.2);color: #ef4444;border: 1px solid #ef4444;}.details-grid {display: grid;9 unmodified linespadding: 1.5rem;}.detail-label {font-size: 0.85rem;color: #8b8ba7;margin-bottom: 0.5rem;}.detail-value {font-size: 1.1rem;font-weight: 600;color: #fff;}.summary-box {background: rgba(124, 58, 237, 0.1);3 unmodified linesmargin-bottom: 2rem;}.summary-title {font-weight: 600;margin-bottom: 0.5rem;color: #a855f7;}.loading {text-align: center;padding: 3rem;display: none;}.loading.visible {display: block;}.spinner {width: 50px;5 unmodified linesmargin: 0 auto 1rem;}@keyframes spin {to {transform: rotate(360deg);}}.error {background: rgba(239, 68, 68, 0.1);3 unmodified linescolor: #ef4444;display: none;}.error.visible {display: block;}footer {text-align: center;margin-top: 3rem;color: #6b6b8a;font-size: 0.9rem;}footer a {color: #7c3aed;text-decoration: none;}/* Node Details Overlay */.node-details-overlay {position: absolute;top: 20px;right: 20px;background: rgba(15, 15, 35, 0.95);border: 1px solid rgba(124, 58, 237, 0.3);border-radius: 12px;padding: 1.5rem;width: 300px;display: none;backdrop-filter: blur(10px);z-index: 100;box-shadow: 0 10px 30px rgba(0,0,0,0.5);pointer-events: auto;}.node-details-overlay.visible {display: block;animation: fadeIn 0.3s ease;}.close-btn {position: absolute;top: 10px;right: 15px;background: none;border: none;color: #8b8ba7;font-size: 1.5rem;cursor: pointer;padding: 0;line-height: 1;width: auto;height: auto;box-shadow: none;}.close-btn:hover {color: #fff;transform: none;box-shadow: none;}</style></head>6 unmodified lines<div class="search-box"><div class="input-group"><input type="text" id="urlInput" placeholder="Entrez une URL à analyser (ex: https://www.lemonde.fr)"autofocus><button id="analyzeBtn" onclick="analyzeUrl()">🔍 Analyser</button></div></div><div class="loading" id="loading">18 unmodified lines<div class="details-grid" id="detailsGrid"></div><div class="graph-section" style="margin-top: 3rem;"><div class="summary-title" style="margin-bottom: 2rem; color: #60a5fa;">🕸️ Réseau Neuro-Symbolique(Ontologie)</div><!-- Debug link --><small style="color: #666; cursor: pointer;"onclick="alert('D3 Loaded: ' + (typeof d3 !== 'undefined'))">Debug: Vérifier D3</small><div id="cy" class="graph-container"></div></div></div><footer><p>SysCRED v2.0 - Prototype de recherche doctorale</p><p>© Dominique S. Loyer - UQAM | <a href="https://doi.org/10.5281/zenodo.17943226" target="_blank">DOI:10.5281/zenodo.17943226</a></p></footer></div><script>// Auto-detect API URL based on environmentconst API_URL = (() => {const hostname = window.location.hostname;if (hostname.includes('huggingface.co') || hostname.includes('hf.space')) {return '';} else if (hostname.includes('onrender.com')) {return '';} else {return 'http://localhost:5001';}})();async function analyzeUrl() {const urlInput = document.getElementById('urlInput');3 unmodified linesconst btn = document.getElementById('analyzeBtn');const inputData = urlInput.value.trim();if (!inputData) {alert('Veuillez entrer une URL');return;}// Reset UIresults.classList.remove('visible');error.classList.remove('visible');loading.classList.add('visible');2 unmodified linestry {const response = await fetch(`${API_URL}/api/verify`, {method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify({input_data: inputData,include_seo: true,include_pagerank: true})});const data = await response.json();if (!response.ok) {throw new Error(data.error || 'Erreur lors de l\'analyse');}displayResults(data);} catch (err) {12 unmodified linesconst summary = document.getElementById('summary');const detailsGrid = document.getElementById('detailsGrid');// Scoreconst score = data.scoreCredibilite || 0;scoreValue.textContent = score.toFixed(2);// Conditional Display: Hide Score Card if TEXT input, show if URLconst isUrl = data.informationEntree && data.informationEntree.startsWith('http');const scoreCard = document.querySelector('.score-card');if (isUrl) {scoreCard.style.display = 'block';// Color based on scorescoreValue.className = 'score-value';credibilityBadge.className = 'credibility-badge';11 unmodified linescredibilityBadge.textContent = '✗ Crédibilité Faible';}} else {// Hide score card for text queries as requestedscoreCard.style.display = 'none';}// Summarysummary.textContent = data.resumeAnalyse || 'Aucun résumé disponible';// Build details HTMLlet detailsHTML = '';// Source reputation from rule analysisconst ruleResults = data.reglesAppliquees || {};const sourceAnalysis = ruleResults.source_analysis || {};if (sourceAnalysis.reputation) {const repColor = sourceAnalysis.reputation === 'High' ? '#22c55e' :sourceAnalysis.reputation === 'Low' ? '#ef4444' : '#eab308';detailsHTML += `<div class="detail-card"><div class="detail-label">🏛️ Réputation Source</div><div class="detail-value" style="color: ${repColor}">${sourceAnalysis.reputation}</div></div>`;}if (sourceAnalysis.domain_age_days) {const years = (sourceAnalysis.domain_age_days / 365).toFixed(1);detailsHTML += `<div class="detail-card"><div class="detail-label">📅 Âge du Domaine</div><div class="detail-value">${years} ans</div></div>`;}// NLP analysisconst nlpAnalysis = data.analyseNLP || {};if (nlpAnalysis.sentiment) {detailsHTML += `<div class="detail-card"><div class="detail-label">💭 Sentiment</div><div class="detail-value">${nlpAnalysis.sentiment.label} (${(nlpAnalysis.sentiment.score * 100).toFixed(0)}%)</div></div>`;}if (nlpAnalysis.coherence_score !== null && nlpAnalysis.coherence_score !== undefined) {detailsHTML += `<div class="detail-card"><div class="detail-label">📊 Cohérence</div><div class="detail-value">${(nlpAnalysis.coherence_score * 100).toFixed(0)}%</div></div>`;}// Add PageRank if availableif (data.pageRankEstimation && data.pageRankEstimation.estimatedPR) {detailsHTML += `<div class="detail-card"><div class="detail-label">📈 PageRank Estimé</div><div class="detail-value">${data.pageRankEstimation.estimatedPR.toFixed(3)}</div></div>`;}// Add SEO score if availableif (data.seoAnalysis && data.seoAnalysis.seoScore) {detailsHTML += `<div class="detail-card"><div class="detail-label">🔍 Score SEO</div><div class="detail-value">${data.seoAnalysis.seoScore}</div></div>`;}// Fact checksconst factChecks = ruleResults.fact_checking || [];if (factChecks.length > 0) {// Add a header for fact checksdetailsHTML += `<div style="grid-column: 1 / -1; margin-top: 1rem; margin-bottom: 0.5rem; font-weight: 600; color: #f472b6;">🕵️ Fact-Checks Trouvés (${factChecks.length})</div>`;factChecks.forEach(fc => {detailsHTML += `<div class="detail-card" style="grid-column: 1 / -1; border-color: rgba(244, 114, 182, 0.3);"><div class="detail-label">🔍 ${fc.publisher || 'Source inconnue'}</div><div class="detail-value" style="font-size: 1rem; margin-bottom: 0.5rem;">"${fc.claim}"</div><div style="display: flex; justify-content: space-between; align-items: center;"><span style="color: #f472b6; font-weight: 700;">Verdict: ${fc.rating}</span><a href="${fc.url}" target="_blank" style="color: #a855f7; text-decoration: none; font-size: 0.9rem;">Lire le rapport →</a></div></div>`;});}detailsGrid.innerHTML = detailsHTML;results.classList.add('visible');// Fetch and render graph with slight delay to ensure DOM is readyrequestAnimationFrame(() => {renderD3Graph();});}async function renderD3Graph() {logDebug("Starting renderD3Graph...");const container = document.getElementById('cy');// Check if D3 is loadedif (typeof d3 === 'undefined') {container.innerHTML = '<p class="error visible">Erreur: D3.js n\'a pas pu être chargé.</p>';logDebug("ERROR: D3 undefined");return;}try {container.innerHTML = '<div class="spinner"></div>'; // Loading statelogDebug("Fetching graph data...");const response = await fetch(`${API_URL}/api/ontology/graph`);const data = await response.json();container.innerHTML = ''; // Clear loadinglogDebug(`Data received. Nodes: ${data.nodes ? data.nodes.length : 0}, Links: ${data.links ? data.links.length : 0}`);if (!data.nodes || data.nodes.length === 0) {container.innerHTML = '<p style="text-align:center; padding:2rem; color:#6b6b8a; width:100%; display:flex; justify-content:center; align-items:center; height:100%;">Ayçune donnée ontologique disponible.</p>';return;}// Get dimensionsconst width = container.clientWidth || 800;const height = container.clientHeight || 500;logDebug(`Container size: ${width}x${height}`);const svg = d3.select(container).append("svg").attr("width", "100%").attr("height", "100%").attr("viewBox", [-width / 2, -height / 2, width, height]).style("background-color", "rgba(0,0,0,0.2)"); // Visible background// ADDED: Overlay for detailsconst overlay = document.createElement('div');overlay.id = 'nodeDetails';overlay.className = 'node-details-overlay';overlay.innerHTML = `<button class="close-btn" onclick="document.getElementById('nodeDetails').classList.remove('visible')">×</button><h3 id="detailTitle" style="color:#fff; margin-bottom:0.5rem; font-size:1.1rem; border-bottom:1px solid rgba(255,255,255,0.1); padding-bottom:0.5rem;"></h3><div id="detailBody" style="font-size:0.9rem; color:#ccc; line-height:1.5;"></div>`;container.appendChild(overlay);logDebug("SVG created. Starting simulation...");// Colors: 1=Purple(Report), 2=Gray(Unknown), 3=Green(Good), 4=Red(Bad)const color = d3.scaleOrdinal().domain([1, 2, 3, 4]).range(["#8b5cf6", "#94a3b8", "#22c55e", "#ef4444"]);const simulation = d3.forceSimulation(data.nodes).force("link", d3.forceLink(data.links).id(d => d.id).distance(120)).force("charge", d3.forceManyBody().strength(-400)).force("center", d3.forceCenter(0, 0));// ADDED: Container click to close overlaysvg.on("click", () => {document.getElementById('nodeDetails').classList.remove('visible');node.attr("stroke", "#fff").attr("stroke-width", 1.5);});// Arrow markersvg.append("defs").selectAll("marker").data(["end"]).join("marker").attr("id", "arrow").attr("viewBox", "0 -5 10 10").attr("refX", 22).attr("refY", 0).attr("markerWidth", 6).attr("markerHeight", 6).attr("orient", "auto").append("path").attr("fill", "#64748b").attr("d", "M0,-5L10,0L0,5");const link = svg.append("g").selectAll("line").data(data.links).join("line").attr("stroke", "#475569").attr("stroke-opacity", 0.6).attr("stroke-width", 2).attr("marker-end", "url(#arrow)");const node = svg.append("g").selectAll("circle").data(data.nodes).join("circle").attr("r", d => d.group === 1 ? 18 : 8).attr("fill", d => color(d.group)).attr("stroke", "#fff").attr("stroke-width", 1.5).style("cursor", "pointer").call(drag(simulation)).on("click", (event, d) => {event.stopPropagation(); // Stop background clickshowNodeDetails(d);// Highlight selectednode.attr("stroke", "#fff").attr("stroke-width", 1.5);d3.select(event.currentTarget).attr("stroke", "#f43f5e").attr("stroke-width", 3);});// Labelsconst text = svg.append("g").selectAll("text").data(data.nodes).join("text").text(d => d.name.length > 20 ? d.name.substring(0, 20) + "..." : d.name).attr("font-size", "11px").attr("fill", "#e0e0e0").attr("dx", 12).attr("dy", 4).style("pointer-events", "none").style("text-shadow", "0 1px 2px black");// Tooltipnode.append("title").text(d => `${d.name}\n(${d.type})`);simulation.on("tick", () => {link.attr("x1", d => d.source.x).attr("y1", d => d.source.y).attr("x2", d => d.target.x).attr("y2", d => d.target.y);node.attr("cx", d => d.x).attr("cy", d => d.y);text.attr("x", d => d.x).attr("y", d => d.y);});// Zoomsvg.call(d3.zoom().scaleExtent([0.1, 4]).on("zoom", (e) => {svg.selectAll('g').attr('transform', e.transform);}));logDebug("Graph rendered successfully.");} catch (err) {console.error("D3 Graph error:", err);const container = document.getElementById('cy');if (container) container.innerHTML = `<p class="error visible">Erreur graphique: ${err.message}</p>`;logDebug(`ERROR EXCEPTION: ${err.message}`);}}function testD3() {logDebug("Starting Static Test...");const container = document.getElementById('cy');container.innerHTML = '';const width = container.clientWidth || 800;const height = container.clientHeight || 500;logDebug(`Container: ${width}x${height}`);try {const svg = d3.select(container).append("svg").attr("width", "100%").attr("height", "100%").attr("viewBox", [-width / 2, -height / 2, width, height]).style("background-color", "#222");svg.append("circle").attr("r", 50).attr("fill", "red").attr("cx", 0).attr("cy", 0);svg.append("text").text("D3 WORKS").attr("fill", "white").attr("x", 0).attr("y", 5).attr("text-anchor", "middle");logDebug("Static Test Complete. You should see a red circle.");} catch (e) {logDebug("Static Test ERROR: " + e.message);alert("Static Test Failed: " + e.message);}}// --- Helper Functions ---function logDebug(msg) {console.log(`[SysCRED Debug] ${msg}`);}function drag(simulation) {function dragstarted(event) {if (!event.active) simulation.alphaTarget(0.3).restart();event.subject.fx = event.subject.x;event.subject.fy = event.subject.y;}function dragged(event) {event.subject.fx = event.x;event.subject.fy = event.y;}function dragended(event) {if (!event.active) simulation.alphaTarget(0);event.subject.fx = null;event.subject.fy = null;}return d3.drag().on("start", dragstarted).on("drag", dragged).on("end", dragended);}function showNodeDetails(d) {const overlay = document.getElementById('nodeDetails');const title = document.getElementById('detailTitle');const body = document.getElementById('detailBody');if(!overlay) return;title.textContent = d.name;let typeColor = "#94a3b8";if(d.group === 1) typeColor = "#8b5cf6"; // Reportif(d.group === 3) typeColor = "#22c55e"; // Goodif(d.group === 4) typeColor = "#ef4444"; // Badbody.innerHTML = `<div style="margin-bottom:0.5rem"><span style="background:${typeColor}; color:white; padding:2px 6px; border-radius:4px; font-size:0.75rem;">${d.type || 'Unknown Type'}</span></div><div><strong>URI:</strong> <br><span style="font-family:monospace; color:#a855f7; word-break:break-all;">${d.id}</span></div>`;overlay.classList.add('visible');}// Allow Enter key to trigger analysisdocument.getElementById('urlInput').addEventListener('keypress', function (e) {if (e.key === 'Enter') {analyzeUrl();}});</script></body>16 unmodified lines17181920212295 unmodified lines1181191201211221231241251261271281296 unmodified lines1361371381391401411421431441451465 unmodified lines1521531541551561571581591609 unmodified lines1701711721731741751761773 unmodified lines1811821831841851861871881891905 unmodified lines1961971981992002012023 unmodified lines2062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542556 unmodified lines26226326426526626726826927027127227327427527627727827928028118 unmodified lines3003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573 unmodified lines3613623633643653663673682 unmodified lines37137237337437537637737837938038138212 unmodified lines39539639739839940040140240340440540640740811 unmodified lines42042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954016 unmodified linesborder: 1px solid rgba(255, 255, 255, 0.1);position: relative;display: block;}* {95 unmodified linestransform: none;}.results { display: none; }.results.visible { display: block; animation: fadeIn 0.5s ease; }@keyframes fadeIn {from { opacity: 0; transform: translateY(20px); }to { opacity: 1; transform: translateY(0); }}.score-card {6 unmodified linesmargin-bottom: 2rem;}.score-value { font-size: 4rem; font-weight: 700; margin: 1rem 0; }.score-high { color: #22c55e; }.score-medium { color: #eab308; }.score-low { color: #ef4444; }.score-label { font-size: 1.2rem; color: #8b8ba7; margin-bottom: 1rem; }.credibility-badge {display: inline-block;5 unmodified linesletter-spacing: 1px;}.badge-high { background: rgba(34, 197, 94, 0.2); color: #22c55e; border: 1px solid #22c55e; }.badge-medium { background: rgba(234, 179, 8, 0.2); color: #eab308; border: 1px solid #eab308; }.badge-low { background: rgba(239, 68, 68, 0.2); color: #ef4444; border: 1px solid #ef4444; }.details-grid {display: grid;9 unmodified linespadding: 1.5rem;}.detail-label { font-size: 0.85rem; color: #8b8ba7; margin-bottom: 0.5rem; }.detail-value { font-size: 1.1rem; font-weight: 600; color: #fff; }.summary-box {background: rgba(124, 58, 237, 0.1);3 unmodified linesmargin-bottom: 2rem;}.summary-title { font-weight: 600; margin-bottom: 0.5rem; color: #a855f7; }.loading { text-align: center; padding: 3rem; display: none; }.loading.visible { display: block; }.spinner {width: 50px;5 unmodified linesmargin: 0 auto 1rem;}@keyframes spin { to { transform: rotate(360deg); } }.error {background: rgba(239, 68, 68, 0.1);3 unmodified linescolor: #ef4444;display: none;}.error.visible { display: block; }footer { text-align: center; margin-top: 3rem; color: #6b6b8a; font-size: 0.9rem; }footer a { color: #7c3aed; text-decoration: none; }/* Backend Toggle Switch */.backend-toggle {display: flex;align-items: center;justify-content: center;gap: 0.75rem;margin-top: 1rem;padding: 0.75rem;background: rgba(0,0,0,0.2);border-radius: 10px;}.backend-toggle label { font-size: 0.85rem; color: #8b8ba7; cursor: pointer; }.backend-toggle .active { color: #a855f7; font-weight: 600; }.toggle-switch { position: relative; width: 50px; height: 26px; }.toggle-switch input { opacity: 0; width: 0; height: 0; }.toggle-slider {position: absolute;cursor: pointer;top: 0; left: 0; right: 0; bottom: 0;background: linear-gradient(135deg, #22c55e, #16a34a);border-radius: 26px;transition: 0.3s;}.toggle-slider:before {position: absolute;content: '';height: 20px;width: 20px;left: 3px;bottom: 3px;background: white;border-radius: 50%;transition: 0.3s;}.toggle-switch input:checked + .toggle-slider { background: linear-gradient(135deg, #7c3aed, #a855f7); }.toggle-switch input:checked + .toggle-slider:before { transform: translateX(24px); }.backend-status { font-size: 0.75rem; color: #6b6b8a; text-align: center; margin-top: 0.5rem; }.backend-status.local { color: #22c55e; }.backend-status.remote { color: #a855f7; }</style></head>6 unmodified lines<div class="search-box"><div class="input-group"><input type="text" id="urlInput" placeholder="Entrez une URL ou du texte à analyser" autofocus><button id="analyzeBtn" onclick="analyzeUrl()">🔍 Analyser</button></div><!-- Backend Toggle --><div class="backend-toggle"><label id="labelLocal" class="active">🖥️ Local</label><div class="toggle-switch"><input type="checkbox" id="backendToggle" onchange="toggleBackend()"><span class="toggle-slider"></span></div><label id="labelRemote">☁️ HF Space</label></div><div class="backend-status local" id="backendStatus">Backend: localhost:5001 (léger, sans ML)</div></div><div class="loading" id="loading">18 unmodified lines<div class="details-grid" id="detailsGrid"></div><div class="graph-section" style="margin-top: 3rem;"><div class="summary-title" style="margin-bottom: 2rem; color: #60a5fa;">🕸️ Réseau Neuro-Symbolique (Ontologie)</div><div id="cy" class="graph-container"></div></div></div><footer><p>SysCRED v2.3.1 - Prototype de recherche doctorale</p><p>© Dominique S. Loyer - UQAM | <a href="https://doi.org/10.5281/zenodo.17943226" target="_blank">DOI: 10.5281/zenodo.17943226</a></p></footer></div><script>// Backend URLs - Auto-detect or manual toggleconst LOCAL_API_URL = 'http://localhost:5001';const REMOTE_API_URL = ''; // Empty = same origin for HF Space// Auto-detect environment on loadlet API_URL = (() => {const hostname = window.location.hostname;if (hostname.includes('hf.space') || hostname.includes('huggingface.co')) {// On HF Space, use same origindocument.getElementById('backendToggle').checked = true;document.getElementById('labelLocal').classList.remove('active');document.getElementById('labelRemote').classList.add('active');document.getElementById('backendStatus').textContent = 'Backend: HF Space (ML complet)';document.getElementById('backendStatus').className = 'backend-status remote';return '';}return LOCAL_API_URL;})();function toggleBackend() {const toggle = document.getElementById('backendToggle');const status = document.getElementById('backendStatus');const labelLocal = document.getElementById('labelLocal');const labelRemote = document.getElementById('labelRemote');if (toggle.checked) {API_URL = REMOTE_API_URL || 'https://domloyer-syscred.hf.space';status.textContent = 'Backend: HF Space (ML complet, plus lent)';status.className = 'backend-status remote';labelLocal.classList.remove('active');labelRemote.classList.add('active');} else {API_URL = LOCAL_API_URL;status.textContent = 'Backend: localhost:5001 (léger, sans ML)';status.className = 'backend-status local';labelLocal.classList.add('active');labelRemote.classList.remove('active');}console.log('[SysCRED] Backend switched to:', API_URL || '(same origin)');}async function analyzeUrl() {const urlInput = document.getElementById('urlInput');3 unmodified linesconst btn = document.getElementById('analyzeBtn');const inputData = urlInput.value.trim();if (!inputData) { alert('Veuillez entrer une URL ou du texte'); return; }results.classList.remove('visible');error.classList.remove('visible');loading.classList.add('visible');2 unmodified linestry {const response = await fetch(`${API_URL}/api/verify`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ input_data: inputData, include_seo: true, include_pagerank: true })});const data = await response.json();if (!response.ok) throw new Error(data.error || 'Erreur lors de l\'analyse');displayResults(data);} catch (err) {12 unmodified linesconst summary = document.getElementById('summary');const detailsGrid = document.getElementById('detailsGrid');const score = data.scoreCredibilite || 0;scoreValue.textContent = score.toFixed(2);const isUrl = data.informationEntree && data.informationEntree.startsWith('http');const scoreCard = document.querySelector('.score-card');if (isUrl) {scoreCard.style.display = 'block';scoreValue.className = 'score-value';credibilityBadge.className = 'credibility-badge';11 unmodified linescredibilityBadge.textContent = '✗ Crédibilité Faible';}} else {scoreCard.style.display = 'none';}summary.textContent = data.resumeAnalyse || 'Aucun résumé disponible';let detailsHTML = '';const ruleResults = data.reglesAppliquees || {};const sourceAnalysis = ruleResults.source_analysis || {};if (sourceAnalysis.reputation) {const repColor = sourceAnalysis.reputation === 'High' ? '#22c55e' : sourceAnalysis.reputation === 'Low' ? '#ef4444' : '#eab308';detailsHTML += `<div class="detail-card"><div class="detail-label">🏛️ Réputation Source</div><div class="detail-value" style="color: ${repColor}">${sourceAnalysis.reputation}</div></div>`;}if (sourceAnalysis.domain_age_days) {const years = (sourceAnalysis.domain_age_days / 365).toFixed(1);detailsHTML += `<div class="detail-card"><div class="detail-label">📅 Âge du Domaine</div><div class="detail-value">${years} ans</div></div>`;}const nlpAnalysis = data.analyseNLP || {};if (nlpAnalysis.sentiment) {detailsHTML += `<div class="detail-card"><div class="detail-label">💭 Sentiment</div><div class="detail-value">${nlpAnalysis.sentiment.label} (${(nlpAnalysis.sentiment.score * 100).toFixed(0)}%)</div></div>`;}if (nlpAnalysis.coherence_score !== null && nlpAnalysis.coherence_score !== undefined) {detailsHTML += `<div class="detail-card"><div class="detail-label">📊 Cohérence</div><div class="detail-value">${(nlpAnalysis.coherence_score * 100).toFixed(0)}%</div></div>`;}if (data.pageRankEstimation && data.pageRankEstimation.estimatedPR) {detailsHTML += `<div class="detail-card"><div class="detail-label">📈 PageRank Estimé</div><div class="detail-value">${data.pageRankEstimation.estimatedPR.toFixed(3)}</div></div>`;}if (data.seoAnalysis && data.seoAnalysis.seoScore) {detailsHTML += `<div class="detail-card"><div class="detail-label">🔍 Score SEO</div><div class="detail-value">${data.seoAnalysis.seoScore}</div></div>`;}const factChecks = ruleResults.fact_checking || [];if (factChecks.length > 0) {detailsHTML += `<div style="grid-column: 1 / -1; margin-top: 1rem; margin-bottom: 0.5rem; font-weight: 600; color: #f472b6;">🕵��� Fact-Checks Trouvés (${factChecks.length})</div>`;factChecks.forEach(fc => {detailsHTML += `<div class="detail-card" style="grid-column: 1 / -1; border-color: rgba(244, 114, 182, 0.3);"><div class="detail-label">🔍 ${fc.publisher || 'Source inconnue'}</div><div class="detail-value" style="font-size: 1rem; margin-bottom: 0.5rem;">"${fc.claim}"</div><div style="display: flex; justify-content: space-between; align-items: center;"><span style="color: #f472b6; font-weight: 700;">Verdict: ${fc.rating}</span><a href="${fc.url}" target="_blank" style="color: #a855f7; text-decoration: none; font-size: 0.9rem;">Lire le rapport →</a></div></div>`;});}detailsGrid.innerHTML = detailsHTML;results.classList.add('visible');requestAnimationFrame(() => renderD3Graph());}async function renderD3Graph() {const container = document.getElementById('cy');if (typeof d3 === 'undefined') { container.innerHTML = '<p class="error visible">Erreur: D3.js non chargé.</p>'; return; }try {container.innerHTML = '<div class="spinner"></div>';const response = await fetch(`${API_URL}/api/ontology/graph`);const data = await response.json();container.innerHTML = '';if (!data.nodes || data.nodes.length === 0) {container.innerHTML = '<p style="text-align:center; padding:2rem; color:#6b6b8a;">Aucune donnée ontologique disponible.</p>';return;}const width = container.clientWidth || 800;const height = container.clientHeight || 500;const svg = d3.select(container).append("svg").attr("width", "100%").attr("height", "100%").attr("viewBox", [-width / 2, -height / 2, width, height]).style("background-color", "rgba(0,0,0,0.2)");const color = d3.scaleOrdinal().domain([1, 2, 3, 4]).range(["#8b5cf6", "#94a3b8", "#22c55e", "#ef4444"]);const simulation = d3.forceSimulation(data.nodes).force("link", d3.forceLink(data.links).id(d => d.id).distance(120)).force("charge", d3.forceManyBody().strength(-400)).force("center", d3.forceCenter(0, 0));svg.append("defs").selectAll("marker").data(["end"]).join("marker").attr("id", "arrow").attr("viewBox", "0 -5 10 10").attr("refX", 22).attr("refY", 0).attr("markerWidth", 6).attr("markerHeight", 6).attr("orient", "auto").append("path").attr("fill", "#64748b").attr("d", "M0,-5L10,0L0,5");const link = svg.append("g").selectAll("line").data(data.links).join("line").attr("stroke", "#475569").attr("stroke-opacity", 0.6).attr("stroke-width", 2).attr("marker-end", "url(#arrow)");const node = svg.append("g").selectAll("circle").data(data.nodes).join("circle").attr("r", d => d.group === 1 ? 18 : 8).attr("fill", d => color(d.group)).attr("stroke", "#fff").attr("stroke-width", 1.5).style("cursor", "pointer").call(d3.drag().on("start", dragstarted).on("drag", dragged).on("end", dragended));const text = svg.append("g").selectAll("text").data(data.nodes).join("text").text(d => d.name.length > 20 ? d.name.substring(0, 20) + "..." : d.name).attr("font-size", "11px").attr("fill", "#e0e0e0").attr("dx", 12).attr("dy", 4).style("pointer-events", "none").style("text-shadow", "0 1px 2px black");node.append("title").text(d => `${d.name}\n(${d.type})`);simulation.on("tick", () => {link.attr("x1", d => d.source.x).attr("y1", d => d.source.y).attr("x2", d => d.target.x).attr("y2", d => d.target.y);node.attr("cx", d => d.x).attr("cy", d => d.y);text.attr("x", d => d.x).attr("y", d => d.y);});svg.call(d3.zoom().scaleExtent([0.1, 4]).on("zoom", (e) => svg.selectAll('g').attr('transform', e.transform)));function dragstarted(event) { if (!event.active) simulation.alphaTarget(0.3).restart(); event.subject.fx = event.subject.x; event.subject.fy = event.subject.y; }function dragged(event) { event.subject.fx = event.x; event.subject.fy = event.y; }function dragended(event) { if (!event.active) simulation.alphaTarget(0); event.subject.fx = null; event.subject.fy = null; }} catch (err) {container.innerHTML = `<p class="error visible">Erreur graphique: ${err.message}</p>`;}}document.getElementById('urlInput').addEventListener('keypress', function(e) { if (e.key === 'Enter') analyzeUrl(); });</script></body>
syscred/static/index.html+156-475