KingNish commited on
Commit
bb15131
1 Parent(s): fac8362

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +529 -12
index.html CHANGED
@@ -39,7 +39,7 @@ a:hover{text-decoration:underline}
39
  .search-box:focus-within+#suggestions,.search-box:hover+#suggestions{display:block;opacity:1;transform:translateY(0)}
40
  #results{width:100%;max-width:700px;margin-top:20px}
41
  .result,.ai-result{margin-bottom:20px;padding:15px;border-radius:8px;background-color:#fff;box-shadow:0 2px 4px rgba(0,0,0,0.1);opacity:0;transform:translateY(10px);transition:opacity .3s ease,transform .3s ease;animation:fadeInUp .5s ease forwards}
42
- .ai-result{background-color:#f0f0f5}
43
  @keyframes fadeInUp {
44
  from{opacity:0;transform:translateY(20px)}
45
  to{opacity:1;transform:translateY(0)}
@@ -55,6 +55,8 @@ to{opacity:1;transform:translateY(0)}
55
  0%{transform:rotate(0deg)}
56
  100%{transform:rotate(360deg)}
57
  }
 
 
58
  #no-results{display:none;text-align:center;padding:20px;font-size:1.1em;color:#555}
59
  .result .actions button{background-color:#f2f2f2;color:#000;border:1px solid #ddd;padding:8px 16px;border-radius:20px;font-size:.9rem;font-weight:700;cursor:pointer;transition:background-color .2s ease,box-shadow .2s ease;margin-right:10px}
60
  .result .actions button:hover{background-color:#e0e0e0;box-shadow:0 2px 4px rgba(0,0,0,0.1)}
@@ -70,10 +72,33 @@ to{opacity:1;transform:translateY(0)}
70
  #loading-more.active{display:block}
71
  .ai-result h2{margin:0 0 10px;font-size:1.5rem;font-weight:700;color:#333}
72
  .ai-result p{color:#444;font-size:.9rem;line-height:1.5em;margin:0;display:flex;flex-direction:column}
73
- .ai-result p span{opacity:0;animation:slideUp .5s forwards;counter-increment:word-count;animation-delay:calc(0.1s * var(--word-count))}
74
- @keyframes slideUp {
75
- 0%{opacity:0;transform:translateY(10px)}
76
- 100%{opacity:1;transform:translateY(0)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  }
78
  </style>
79
  </head>
@@ -102,23 +127,515 @@ to{opacity:1;transform:translateY(0)}
102
  <div id="summaryPopup" class="summary-popup" style="display: none;">
103
  <span class="close">×</span>
104
  <div class="content">
105
- <div class="loading">
106
- <div class="loading-spinner"></div>
107
- </div>
 
108
  <div id="summaryContent"></div>
109
  </div>
110
  </div>
111
  <div id="answerPopup" class="answer-popup" style="display: none;">
112
  <span class="close">×</span>
113
  <div class="content">
114
- <div class="loading">
115
- <div class="loading-spinner"></div>
116
- </div>
 
117
  <div id="answerContent"></div>
118
  </div>
119
  </div>
120
  <script>
121
- const BASE_URL="https://oevortex-webscout-api.hf.space",searchForm=document.getElementById("search-form"),searchQueryInput=document.getElementById("search-query"),resultsContainer=document.getElementById("results"),suggestionsContainer=document.getElementById("suggestions"),loadingOverlay=document.querySelector(".loading-overlay"),noResultsMessage=document.getElementById("no-results"),loadingMoreIndicator=document.getElementById("loading-more"),aiResponseContainer=document.getElementById("ai-response"),INITIAL_RESULTS=5,CACHED_RESULTS=50,RESULTS_PER_PAGE=10;let allResultsFetched=!1;const seenUrls=new Set;let suggestionRequestTimeout,selectedSuggestionIndex=-1,cachedSearchResults=[];const suggestionCache={};let prefetchTimeout,startTime,allResults=[];function debounce(e,t){return function(){clearTimeout(suggestionRequestTimeout),suggestionRequestTimeout=setTimeout((()=>{e.apply(this,arguments)}),t)}}async function fetchSuggestions(e){if(suggestionCache[e])return suggestionCache[e];try{const t=await fetch(`${BASE_URL}/api/suggestions?q=${encodeURIComponent(e)}`);if(t.ok){const n=await t.json();return suggestionCache[e]=n,n}return console.error("Error fetching suggestions:",t.status),[]}catch(e){return console.error("Error fetching suggestions:",e),[]}}function displaySuggestions(e){if(suggestionsContainer.innerHTML="",0===e.length||""===searchQueryInput.value.trim())return void(suggestionsContainer.style.display="none");const t=document.createElement("ul");e.forEach(((e,n)=>{const s=document.createElement("li");s.textContent=e.phrase,s.addEventListener("click",(()=>{searchQueryInput.value=e.phrase,suggestionsContainer.style.display="none",performSearch(e.phrase)})),s.addEventListener("focus",(()=>{selectedSuggestionIndex=n,updateSuggestionSelection()})),t.appendChild(s)})),suggestionsContainer.appendChild(t),suggestionsContainer.style.display="block"}function updateSuggestionSelection(){suggestionsContainer.querySelectorAll("li").forEach(((e,t)=>{e.classList.toggle("selected",t===selectedSuggestionIndex)}))}function showLoading(){loadingOverlay.style.display="block"}function hideLoading(){loadingOverlay.style.display="none"}async function performSearch(e){showLoading(),aiResponseContainer.style.display="none",suggestionsContainer.style.display="none",startTime=performance.now(),seenUrls.clear(),allResultsFetched=!1,resultsContainer.innerHTML="",noResultsMessage.style.display="none",loadingMoreIndicator.classList.remove("active");displayResults(await fetchResults(e,INITIAL_RESULTS)),hideLoading(),fetchResults(e,CACHED_RESULTS).then((e=>{cachedSearchResults=removeDuplicateResults(e),allResults=allResults.concat(cachedSearchResults),displayResults(cachedSearchResults.slice(INITIAL_RESULTS,RESULTS_PER_PAGE),!0),cachedSearchResults.length>RESULTS_PER_PAGE&&(allResultsFetched=!1,loadingMoreIndicator.classList.add("active"))})),fetchAIResponse(e).then((e=>{displayAIResponse(e),aiResponseContainer.style.display="block"})).catch((e=>{console.error("Error fetching AI response:",e)})),updateURLWithQuery(e)}async function fetchAIResponse(e){try{const t=encodeURIComponent(e),n=await fetch(`${BASE_URL}/api/ask_website?url=https://google.com/search?q=${t}&question=${t}`);if(n.ok){return await n.json()}return console.error("Error fetching AI response from website:",n.status),null}catch(e){return console.error("Error fetching AI response from website:",e),null}}function displayAIResponse(e){if(aiResponseContainer.innerHTML="",e){const t=document.createElement("div");t.classList.add("ai-result");const n=document.createElement("h2");n.textContent="AI Response",t.appendChild(n);const s=document.createElement("p"),o=decodeHtml(e).split(" ");let r="",a=0,i=10;!function e(){if(a<o.length){const t=o[a];if(r.length+t.length+1>100){const e=document.createElement("span");e.textContent=r.trim(),s.appendChild(e),r=t+" "}else r+=t+" ";a++,setTimeout(e,i)}else{const e=document.createElement("span");e.textContent=r.trim(),s.appendChild(e)}}(),s.setAttribute("style","font-size: 1rem; line-height: 1.5rem;"),t.appendChild(s),aiResponseContainer.appendChild(t),setTimeout((()=>{t.classList.add("show"),aiResponseContainer.style.display="block",hideLoading()}),100)}}function updateURLWithQuery(e){const t=`${window.location.pathname}?query=${encodeURIComponent(e)}`;window.history.pushState({path:t},"",t)}function removeDuplicateResults(e){const t=[],n=new Set;for(const s of e)n.has(s.href)||(n.add(s.href),t.push(s));return t}async function fetchResults(e,t){const n=await fetch(`${BASE_URL}/api/search?q=${encodeURIComponent(e)}&max_results=${t}`);if(!n.ok)return displayError("An error occurred while fetching results."),hideLoading(),[];return await n.json()}searchQueryInput.addEventListener("input",(()=>{clearTimeout(prefetchTimeout);const e=searchQueryInput.value.trim();""!==e?prefetchTimeout=setTimeout((async()=>{displaySuggestions(await fetchSuggestions(e))}),100):suggestionsContainer.style.display="none"}));const summaryPopup=document.getElementById("summaryPopup"),summaryContent=document.getElementById("summaryContent"),answerPopup=document.getElementById("answerPopup"),answerContent=document.getElementById("answerContent"),summaryCache={},answerCache={};function displayResults(e,t=!1){t||(resultsContainer.innerHTML="");if(e.filter((e=>!seenUrls.has(e.href))).forEach(((e,t)=>{seenUrls.add(e.href);const n=document.createElement("div");n.classList.add("result");const s=document.createElement("h3"),o=document.createElement("a");o.href=e.href,o.textContent=e.title,o.target="_blank",o.rel="noopener noreferrer",s.appendChild(o);const r=document.createElement("div");r.classList.add("url");const a=document.createElement("a");a.href=e.href,a.textContent=e.href,a.target="_blank",a.rel="noopener noreferrer",r.appendChild(a);const i=document.createElement("p");i.textContent=e.body,n.appendChild(s),n.appendChild(r),n.appendChild(i);const l=document.createElement("div");l.classList.add("actions");const c=document.createElement("button");c.textContent="Summarize this site",c.addEventListener("click",(()=>{showSummaryPopup(e.href)})),l.appendChild(c);const u=document.createElement("button");u.textContent="Answer from this site",u.addEventListener("click",(()=>{showAnswerPopup(e.href)})),l.appendChild(u),n.appendChild(l),resultsContainer.appendChild(n),setTimeout((()=>{n.classList.add("show")}),100*t)})),0===resultsContainer.children.length?noResultsMessage.style.display="block":noResultsMessage.style.display="none",!t){const e=(performance.now()/2-startTime/2).toFixed(2);document.getElementById("results-info").textContent=`About ${e} milliseconds`}}function displayError(e){resultsContainer.innerHTML="";const t=document.createElement("p");t.textContent=e,t.style.color="red",resultsContainer.appendChild(t)}function getQueryParameter(e){return new URLSearchParams(window.location.search).get(e)}function decodeHtml(e){var t=document.createElement("textarea");return t.innerHTML=e,t.value}function showSummaryPopup(e){summaryContent.innerHTML="",summaryPopup.querySelector(".loading").style.display="block",summaryPopup.style.display="block",summaryCache[e]?displaySummary(summaryCache[e]):fetchWebsiteSummary(e).then((t=>{summaryCache[e]=t,displaySummary(t)})).catch((e=>{console.error("Error fetching summary:",e),displaySummary("Error fetching summary.")}))}function displaySummary(e){summaryPopup.querySelector(".loading").style.display="none",summaryContent.textContent=e}async function fetchWebsiteSummary(e){const t=await fetch(`${BASE_URL}/api/website_summarizer?url=${e}`);if(!t.ok)throw new Error("Error fetching website summary.");return(await t.json())[0]||"No summary available"}function showAnswerPopup(e){if(answerContent.innerHTML="",answerPopup.querySelector(".loading").style.display="block",answerPopup.style.display="block",answerCache[e])displayAnswer(answerCache[e]);else{const t=searchQueryInput.value;fetchWebsiteAnswer(e,t).then((t=>{answerCache[e]=t,displayAnswer(t)})).catch((e=>{console.error("Error fetching answer:",e),displayAnswer("Error fetching answer.")}))}}function displayAnswer(e){answerPopup.querySelector(".loading").style.display="none",answerContent.textContent=e}async function fetchWebsiteAnswer(e,t){const n=await fetch(`${BASE_URL}/api/ask_website?url=${e}&question=${encodeURIComponent(t)}`);if(!n.ok)throw new Error("Error fetching answer from website.");return(await n.json())[0]||"No answer found."}searchQueryInput.addEventListener("input",debounce((async()=>{selectedSuggestionIndex=-1;const e=searchQueryInput.value;if(""===e.trim())return void(suggestionsContainer.style.display="none");displaySuggestions(await fetchSuggestions(e))}),500)),searchQueryInput.addEventListener("focus",(()=>{""!==searchQueryInput.value.trim()&&(suggestionsContainer.style.display="block")})),document.addEventListener("click",(e=>{searchForm.contains(e.target)||(suggestionsContainer.style.display="none")})),searchQueryInput.addEventListener("keydown",(async e=>{if("ArrowUp"===e.key||"ArrowDown"===e.key){e.preventDefault();const t=suggestionsContainer.querySelectorAll("li"),n=t.length;selectedSuggestionIndex="ArrowUp"===e.key?(selectedSuggestionIndex-1+n)%n:(selectedSuggestionIndex+1)%n,updateSuggestionSelection(),-1!==selectedSuggestionIndex&&t[selectedSuggestionIndex]&&(searchQueryInput.value=t[selectedSuggestionIndex].textContent,t[selectedSuggestionIndex].focus())}else if("Enter"===e.key&&-1!==selectedSuggestionIndex){e.preventDefault();const t=suggestionsContainer.querySelectorAll("li")[selectedSuggestionIndex];t&&(searchQueryInput.value=t.textContent,suggestionsContainer.style.display="none",performSearch(searchQueryInput.value))}})),searchForm.addEventListener("submit",(async e=>{e.preventDefault(),selectedSuggestionIndex=-1;performSearch(searchQueryInput.value)})),window.addEventListener("scroll",(()=>{if(allResultsFetched)return;const{scrollTop:e,scrollHeight:t,clientHeight:n}=document.documentElement;if(e+n>=t-100&&allResults.length>seenUrls.size){loadingMoreIndicator.classList.add("active");const e=allResults.slice(seenUrls.size,seenUrls.size+RESULTS_PER_PAGE);setTimeout((()=>{displayResults(e,!0);for(const t of e)seenUrls.add(t.href);allResults.length===seenUrls.size&&(allResultsFetched=!0,loadingMoreIndicator.classList.remove("active"))}),300)}})),window.addEventListener("load",(()=>{const e=getQueryParameter("query");e&&(searchQueryInput.value=e,performSearch(e))})),summaryPopup.querySelector(".close").addEventListener("click",(()=>{summaryPopup.style.display="none"})),answerPopup.querySelector(".close").addEventListener("click",(()=>{answerPopup.style.display="none"}));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  </script>
123
  </body>
124
  </html>
 
39
  .search-box:focus-within+#suggestions,.search-box:hover+#suggestions{display:block;opacity:1;transform:translateY(0)}
40
  #results{width:100%;max-width:700px;margin-top:20px}
41
  .result,.ai-result{margin-bottom:20px;padding:15px;border-radius:8px;background-color:#fff;box-shadow:0 2px 4px rgba(0,0,0,0.1);opacity:0;transform:translateY(10px);transition:opacity .3s ease,transform .3s ease;animation:fadeInUp .5s ease forwards}
42
+ .ai-result{background-color:#f0f0f5;width:100%;max-width:800px}
43
  @keyframes fadeInUp {
44
  from{opacity:0;transform:translateY(20px)}
45
  to{opacity:1;transform:translateY(0)}
 
55
  0%{transform:rotate(0deg)}
56
  100%{transform:rotate(360deg)}
57
  }
58
+ .loading-spinner{width:40px;height:40px;border-radius:50%;border:5px solid #f3f3f3;border-top:5px solid #3498db;animation:spin 1.2s linear infinite}
59
+ .loading-text{margin-left:10px;font-size:1rem;color:#333}
60
  #no-results{display:none;text-align:center;padding:20px;font-size:1.1em;color:#555}
61
  .result .actions button{background-color:#f2f2f2;color:#000;border:1px solid #ddd;padding:8px 16px;border-radius:20px;font-size:.9rem;font-weight:700;cursor:pointer;transition:background-color .2s ease,box-shadow .2s ease;margin-right:10px}
62
  .result .actions button:hover{background-color:#e0e0e0;box-shadow:0 2px 4px rgba(0,0,0,0.1)}
 
72
  #loading-more.active{display:block}
73
  .ai-result h2{margin:0 0 10px;font-size:1.5rem;font-weight:700;color:#333}
74
  .ai-result p{color:#444;font-size:.9rem;line-height:1.5em;margin:0;display:flex;flex-direction:column}
75
+ .ai-result .actions {
76
+ display: flex;
77
+ justify-content: flex-end; /* Align buttons to the right */
78
+ margin-top: 10px;
79
+ }
80
+
81
+ .ai-result .actions button {
82
+ background-color: #f2f2f2;
83
+ color: #000;
84
+ border: 1px solid #ddd;
85
+ padding: 8px 12px; /* Adjust padding if needed */
86
+ border-radius: 20px;
87
+ font-size: .9rem;
88
+ font-weight: 700;
89
+ cursor: pointer;
90
+ transition: background-color .2s ease, box-shadow .2s ease;
91
+ margin-left: 10px; /* Add space between buttons */
92
+ }
93
+
94
+ .ai-result .actions button:hover {
95
+ background-color: #e0e0e0;
96
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
97
+ }
98
+
99
+ .ai-result .actions button i { /* Style Font Awesome icons */
100
+ font-size: 1.2rem; /* Adjust icon size as needed */
101
+ color: #333;
102
  }
103
  </style>
104
  </head>
 
127
  <div id="summaryPopup" class="summary-popup" style="display: none;">
128
  <span class="close">×</span>
129
  <div class="content">
130
+ <div class="loading">
131
+ <div class="loading-spinner"></div>
132
+ <p class="loading-text">Loading...</p>
133
+ </div>
134
  <div id="summaryContent"></div>
135
  </div>
136
  </div>
137
  <div id="answerPopup" class="answer-popup" style="display: none;">
138
  <span class="close">×</span>
139
  <div class="content">
140
+ <div class="loading">
141
+ <div class="loading-spinner"></div>
142
+ <p class="loading-text">Loading...</p>
143
+ </div>
144
  <div id="answerContent"></div>
145
  </div>
146
  </div>
147
  <script>
148
+ const BASE_URL = "https://oevortex-webscout-api.hf.space";
149
+ const searchForm = document.getElementById("search-form");
150
+ const searchQueryInput = document.getElementById("search-query");
151
+ const resultsContainer = document.getElementById("results");
152
+ const suggestionsContainer = document.getElementById("suggestions");
153
+ const loadingOverlay = document.querySelector('.loading-overlay');
154
+ const noResultsMessage = document.getElementById('no-results');
155
+ const loadingMoreIndicator = document.getElementById('loading-more');
156
+ const aiResponseContainer = document.getElementById('ai-response');
157
+ const INITIAL_RESULTS = 5;
158
+ const CACHED_RESULTS = 50;
159
+ const RESULTS_PER_PAGE = 5;
160
+ let allResultsFetched = false;
161
+ const seenUrls = new Set();
162
+ let selectedSuggestionIndex = -1;
163
+ let suggestionRequestTimeout;
164
+ let cachedSearchResults = [];
165
+ const suggestionCache = {};
166
+ let prefetchTimeout;
167
+ let allResults = [];
168
+ let startTime;
169
+
170
+ function debounce(func, delay) {
171
+ return function() {
172
+ clearTimeout(suggestionRequestTimeout);
173
+ suggestionRequestTimeout = setTimeout(() => {
174
+ func.apply(this, arguments);
175
+ }, delay);
176
+ };
177
+ }
178
+ async function fetchSuggestions(query) {
179
+ if (suggestionCache[query]) {
180
+ return suggestionCache[query];
181
+ }
182
+ try {
183
+ const response = await fetch(`${BASE_URL}/api/suggestions?q=${encodeURIComponent(query)}`);
184
+ if (response.ok) {
185
+ const suggestions = await response.json();
186
+ suggestionCache[query] = suggestions;
187
+ return suggestions;
188
+ } else {
189
+ console.error("Error fetching suggestions:", response.status);
190
+ return [];
191
+ }
192
+ } catch (error) {
193
+ console.error("Error fetching suggestions:", error);
194
+ return [];
195
+ }
196
+ }
197
+ searchQueryInput.addEventListener("input", () => {
198
+ clearTimeout(prefetchTimeout);
199
+ const searchQuery = searchQueryInput.value.trim();
200
+ if (searchQuery === "") {
201
+ suggestionsContainer.style.display = "none";
202
+ return;
203
+ }
204
+ prefetchTimeout = setTimeout(async () => {
205
+ const suggestions = await fetchSuggestions(searchQuery);
206
+ displaySuggestions(suggestions);
207
+ }, 100);
208
+ });
209
+
210
+ function displaySuggestions(suggestions) {
211
+ suggestionsContainer.innerHTML = "";
212
+ if (suggestions.length === 0 || searchQueryInput.value.trim() === "") {
213
+ suggestionsContainer.style.display = "none";
214
+ return;
215
+ }
216
+ const suggestionList = document.createElement("ul");
217
+ suggestions.forEach((suggestion, index) => {
218
+ const listItem = document.createElement("li");
219
+ listItem.textContent = suggestion.phrase;
220
+ listItem.addEventListener("click", () => {
221
+ searchQueryInput.value = suggestion.phrase;
222
+ suggestionsContainer.style.display = "none";
223
+ performSearch(suggestion.phrase);
224
+ });
225
+ listItem.addEventListener("focus", () => {
226
+ selectedSuggestionIndex = index;
227
+ updateSuggestionSelection();
228
+ });
229
+ suggestionList.appendChild(listItem);
230
+ });
231
+ suggestionsContainer.appendChild(suggestionList);
232
+ suggestionsContainer.style.display = "block";
233
+ }
234
+
235
+ function updateSuggestionSelection() {
236
+ const suggestionItems = suggestionsContainer.querySelectorAll("li");
237
+ suggestionItems.forEach((item, index) => {
238
+ item.classList.toggle("selected", index === selectedSuggestionIndex);
239
+ });
240
+ }
241
+
242
+ function showLoading() {
243
+ loadingOverlay.style.display = 'block';
244
+ }
245
+
246
+ function hideLoading() {
247
+ loadingOverlay.style.display = 'none';
248
+ }
249
+ async function performSearch(query) {
250
+ showLoading();
251
+ aiResponseContainer.style.display = 'none';
252
+ suggestionsContainer.style.display = "none";
253
+ startTime = performance.now();
254
+ seenUrls.clear();
255
+ allResultsFetched = false;
256
+ resultsContainer.innerHTML = '';
257
+ noResultsMessage.style.display = 'none';
258
+ loadingMoreIndicator.classList.remove('active');
259
+ speechSynthesis.cancel();
260
+ const initialResults = await fetchResults(query, INITIAL_RESULTS);
261
+ displayResults(initialResults);
262
+ hideLoading();
263
+ fetchResults(query, CACHED_RESULTS).then(cachedResults => {
264
+ cachedSearchResults = removeDuplicateResults(cachedResults);
265
+ allResults = allResults.concat(cachedSearchResults);
266
+ displayResults(cachedSearchResults.slice(INITIAL_RESULTS, RESULTS_PER_PAGE), true);
267
+ if (cachedSearchResults.length > RESULTS_PER_PAGE) {
268
+ allResultsFetched = false;
269
+ loadingMoreIndicator.classList.add('active');
270
+ }
271
+ });
272
+ fetchAIResponse(query).then(aiResponse => {
273
+ displayAIResponse(aiResponse);
274
+ aiResponseContainer.style.display = 'block';
275
+ }).catch(error => {
276
+ console.error("Error fetching AI response:", error);
277
+ });
278
+ updateURLWithQuery(query);
279
+ }
280
+ async function fetchAIResponse(query) {
281
+ try {
282
+ const encodedQuery = encodeURIComponent(query);
283
+ const websiteURL = 'https://google.com/search?q=${encodedQuery}'
284
+ const response = await fetch(`${BASE_URL}/api/ask_website?url=https://google.com/search?q=${encodedQuery}&question=Answer this question from google search result ${encodedQuery}&model=gpt-3.5`);
285
+ if (response.ok) {
286
+ const aiResponse = await response.json();
287
+ return aiResponse;
288
+ } else {
289
+ console.error("Error fetching AI response from website:", response.status);
290
+ return null;
291
+ }
292
+ } catch (error) {
293
+ console.error("Error fetching AI response from website:", error);
294
+ return null;
295
+ }
296
+ }
297
+
298
+ function displayAIResponse(response) {
299
+ aiResponseContainer.innerHTML = '';
300
+ if (response) {
301
+ const aiResultElement = document.createElement('div');
302
+ aiResultElement.classList.add('ai-result');
303
+ const aiHeading = document.createElement('h2');
304
+ aiHeading.textContent = "AI Response";
305
+ aiResultElement.appendChild(aiHeading);
306
+ const aiText = document.createElement('p');
307
+ const decodedResponse = decodeHtml(response);
308
+ const msg = new SpeechSynthesisUtterance(decodedResponse);
309
+ speechSynthesis.speak(msg);
310
+ aiText.textContent = decodedResponse;
311
+ const pauseButton = document.createElement('button');
312
+ pauseButton.id = 'pause';
313
+ pauseButton.innerHTML = '<i class="fas fa-pause"></i>';
314
+ const stopButton = document.createElement('button');
315
+ stopButton.id = 'stop';
316
+ stopButton.innerHTML = '<i class="fas fa-stop"></i>';
317
+ let isPaused = false;
318
+ let isStoped = false;
319
+ pauseButton.addEventListener('click', () => {
320
+ if ('speechSynthesis' in window) {
321
+ if (isPaused) {
322
+ window.speechSynthesis.resume();
323
+ isPaused = false;
324
+ stopButton.style.display = 'inline-block';
325
+ pauseButton.innerHTML = '<i class="fas fa-pause"></i>';
326
+ } else {
327
+ window.speechSynthesis.pause();
328
+ isPaused = true;
329
+ stopButton.style.display = 'none';
330
+ pauseButton.innerHTML = '<i class="fas fa-play"></i>';
331
+ }
332
+ }
333
+ });
334
+
335
+ stopButton.addEventListener('click', () => {
336
+ if ('speechSynthesis' in window) {
337
+ if (isStoped){
338
+ speechSynthesis.speak(msg);
339
+ isPaused = false;
340
+ isStoped = false;
341
+ pauseButton.innerHTML = '<i class="fas fa-pause"></i>';
342
+ pauseButton.style.display = 'inline-block';
343
+ stopButton.innerHTML = '<i class="fas fa-stop"></i>';
344
+ }else{
345
+ window.speechSynthesis.cancel();
346
+ isPaused = false;
347
+ isStoped = true;
348
+ pauseButton.style.display = 'none';
349
+ stopButton.innerHTML = '<i class="fas fa-play"></i>'; }
350
+ }
351
+ });
352
+
353
+ // Add the buttons to the actions container
354
+ aiResultElement.appendChild(pauseButton);
355
+ aiResultElement.appendChild(stopButton);
356
+
357
+ // Style the AI response text
358
+ aiText.setAttribute('style', 'font-size: 1rem; line-height: 1.5rem;');
359
+ aiResultElement.appendChild(aiText);
360
+ aiResponseContainer.appendChild(aiResultElement);
361
+ }
362
+ }
363
+
364
+ function updateURLWithQuery(query) {
365
+ const newURL = `${window.location.pathname}?query=${encodeURIComponent(query)}`;
366
+ window.history.pushState({
367
+ path: newURL
368
+ }, '', newURL);
369
+ }
370
+
371
+ function removeDuplicateResults(results) {
372
+ const uniqueResults = [];
373
+ const seen = new Set();
374
+ for (const result of results) {
375
+ if (!seen.has(result.href)) {
376
+ seen.add(result.href);
377
+ uniqueResults.push(result);
378
+ }
379
+ }
380
+ return uniqueResults;
381
+ }
382
+
383
+ async function fetchResults(query, resultsPerPage) {
384
+ const response = await fetch(`${BASE_URL}/api/search?q=${encodeURIComponent(query)}&max_results=${resultsPerPage}`);
385
+ if (!response.ok) {
386
+ displayError("An error occurred while fetching results.");
387
+ hideLoading();
388
+ return [];
389
+ }
390
+ const searchResults = await response.json();
391
+ return searchResults;
392
+ }
393
+
394
+ const summaryPopup = document.getElementById('summaryPopup');
395
+ const summaryContent = document.getElementById('summaryContent');
396
+ const answerPopup = document.getElementById('answerPopup');
397
+ const answerContent = document.getElementById('answerContent');
398
+ const summaryCache = {};
399
+ const answerCache = {};
400
+
401
+ function displayResults(results, append = false) {
402
+ if (!append) {
403
+ resultsContainer.innerHTML = '';
404
+ }
405
+ const newResults = results.filter(result => !seenUrls.has(result.href));
406
+ newResults.forEach((result, index) => {
407
+ seenUrls.add(result.href);
408
+ const resultElement = document.createElement("div");
409
+ resultElement.classList.add("result");
410
+ const titleElement = document.createElement("h3");
411
+ const titleLink = document.createElement("a");
412
+ titleLink.href = result.href;
413
+ titleLink.textContent = result.title;
414
+ titleLink.target = "_blank";
415
+ titleLink.rel = "noopener noreferrer";
416
+ titleElement.appendChild(titleLink);
417
+ const urlElement = document.createElement("div");
418
+ urlElement.classList.add("url");
419
+ const urlLink = document.createElement("a");
420
+ urlLink.href = result.href;
421
+ urlLink.textContent = result.href;
422
+ urlLink.target = "_blank";
423
+ urlLink.rel = "noopener noreferrer";
424
+ urlElement.appendChild(urlLink);
425
+ const descriptionElement = document.createElement("p");
426
+ descriptionElement.textContent = result.body;
427
+ resultElement.appendChild(titleElement);
428
+ resultElement.appendChild(urlElement);
429
+ resultElement.appendChild(descriptionElement);
430
+ const actionsContainer = document.createElement('div');
431
+ actionsContainer.classList.add('actions');
432
+ const summarizeButton = document.createElement('button');
433
+ summarizeButton.textContent = 'Summarize this site';
434
+ summarizeButton.addEventListener('click', () => {
435
+ showSummaryPopup(result.href);
436
+ });
437
+ actionsContainer.appendChild(summarizeButton);
438
+ const answerButton = document.createElement('button');
439
+ answerButton.textContent = 'Answer from this site';
440
+ answerButton.addEventListener('click', () => {
441
+ showAnswerPopup(result.href);
442
+ });
443
+ actionsContainer.appendChild(answerButton);
444
+ resultElement.appendChild(actionsContainer);
445
+ resultsContainer.appendChild(resultElement);
446
+ setTimeout(() => {
447
+ resultElement.classList.add("show");
448
+ }, 1 * index);
449
+ });
450
+ if (resultsContainer.children.length === 0) {
451
+ noResultsMessage.style.display = 'block';
452
+ } else {
453
+ noResultsMessage.style.display = 'none';
454
+ }
455
+ if (!append) {
456
+ const endTime = performance.now();
457
+ const timeTaken = (endTime/2 - startTime/2).toFixed(2);
458
+ document.getElementById('results-info').textContent = `About ${timeTaken} milliseconds`;
459
+ }
460
+ }
461
+
462
+ function displayError(message) {
463
+ resultsContainer.innerHTML = '';
464
+ const errorElement = document.createElement("p");
465
+ errorElement.textContent = message;
466
+ errorElement.style.color = "red";
467
+ resultsContainer.appendChild(errorElement);
468
+ }
469
+
470
+ searchQueryInput.addEventListener("input", debounce(async () => {
471
+ selectedSuggestionIndex = -1;
472
+ const searchQuery = searchQueryInput.value;
473
+ if (searchQuery.trim() === "") {
474
+ suggestionsContainer.style.display = "none";
475
+ return;
476
+ }
477
+ const suggestions = await fetchSuggestions(searchQuery);
478
+ displaySuggestions(suggestions);
479
+ }, 500));
480
+
481
+ searchQueryInput.addEventListener("focus", () => {
482
+ if (searchQueryInput.value.trim() !== "") {
483
+ suggestionsContainer.style.display = "block";
484
+ }
485
+ });
486
+
487
+ document.addEventListener("click", (event) => {
488
+ if (!searchForm.contains(event.target)) {
489
+ suggestionsContainer.style.display = "none";
490
+ }
491
+ });
492
+
493
+ searchQueryInput.addEventListener("keydown", async (event) => {
494
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
495
+ event.preventDefault();
496
+ const suggestionItems = suggestionsContainer.querySelectorAll("li");
497
+ const numSuggestions = suggestionItems.length;
498
+ if (event.key === "ArrowUp") {
499
+ selectedSuggestionIndex = (selectedSuggestionIndex - 1 + numSuggestions) % numSuggestions;
500
+ } else {
501
+ selectedSuggestionIndex = (selectedSuggestionIndex + 1) % numSuggestions;
502
+ }
503
+ updateSuggestionSelection();
504
+ if (selectedSuggestionIndex !== -1 && suggestionItems[selectedSuggestionIndex]) {
505
+ searchQueryInput.value = suggestionItems[selectedSuggestionIndex].textContent;
506
+ suggestionItems[selectedSuggestionIndex].focus();
507
+ }
508
+ } else if (event.key === "Enter" && selectedSuggestionIndex !== -1) {
509
+ event.preventDefault();
510
+ const selectedSuggestion = suggestionsContainer.querySelectorAll("li")[selectedSuggestionIndex];
511
+ if (selectedSuggestion) {
512
+ searchQueryInput.value = selectedSuggestion.textContent;
513
+ suggestionsContainer.style.display = "none";
514
+ performSearch(searchQueryInput.value);
515
+ }
516
+ }
517
+ });
518
+
519
+ searchForm.addEventListener("submit", async (event) => {
520
+ event.preventDefault();
521
+ selectedSuggestionIndex = -1;
522
+ const searchQuery = searchQueryInput.value;
523
+ performSearch(searchQuery);
524
+ });
525
+
526
+ window.addEventListener('scroll', () => {
527
+ if (allResultsFetched) return;
528
+ const {
529
+ scrollTop,
530
+ scrollHeight,
531
+ clientHeight
532
+ } = document.documentElement;
533
+ const isNearBottom = scrollTop + clientHeight >= scrollHeight - 100;
534
+ if (isNearBottom && allResults.length > seenUrls.size) {
535
+ loadingMoreIndicator.classList.add('active');
536
+ const resultsToDisplay = allResults.slice(seenUrls.size, seenUrls.size + RESULTS_PER_PAGE);
537
+ setTimeout(() => {
538
+ displayResults(resultsToDisplay, true);
539
+ for (const result of resultsToDisplay) {
540
+ seenUrls.add(result.href);
541
+ }
542
+ if (allResults.length === seenUrls.size) {
543
+ allResultsFetched = true;
544
+ loadingMoreIndicator.classList.remove('active');
545
+ }
546
+ }, 300);
547
+ }
548
+ });
549
+
550
+ function getQueryParameter(name) {
551
+ const urlParams = new URLSearchParams(window.location.search);
552
+ return urlParams.get(name);
553
+ }
554
+
555
+ window.addEventListener('load', () => {
556
+ const initialQuery = getQueryParameter('query');
557
+ if (initialQuery) {
558
+ searchQueryInput.value = initialQuery;
559
+ performSearch(initialQuery);
560
+ }
561
+ });
562
+
563
+ function decodeHtml(html) {
564
+ var txt = document.createElement("textarea");
565
+ txt.innerHTML = html;
566
+ return txt.value;
567
+ }
568
+
569
+ function showSummaryPopup(url) {
570
+ summaryContent.innerHTML = '';
571
+ summaryPopup.querySelector('.loading').style.display = 'block';
572
+ summaryPopup.style.display = 'block';
573
+ if (summaryCache[url]) {
574
+ displaySummary(summaryCache[url]);
575
+ } else {
576
+ fetchWebsiteSummary(url).then(summary => {
577
+ summaryCache[url] = summary;
578
+ displaySummary(summary);
579
+ }).catch(error => {
580
+ console.error('Error fetching summary:', error);
581
+ displaySummary('Error fetching summary.');
582
+ });
583
+ }
584
+ }
585
+
586
+ function displaySummary(summary) {
587
+ summaryPopup.querySelector('.loading').style.display = 'none';
588
+ summaryContent.textContent = summary;
589
+ }
590
+
591
+ async function fetchWebsiteSummary(url) {
592
+ const response = await fetch(`${BASE_URL}/api/ask_website?url=${url}&question=${encodeURIComponent("Summarize this site in Detail, Do not start with any intro, Just start summarizing. Summarize in this manner which is very important to human user.")}&model=mixtral-8x7b`);
593
+ if (!response.ok) {
594
+ throw new Error('Error fetching website summary.');
595
+ }
596
+ const data = await response.json();
597
+ return data[0] || 'No summary available';
598
+ }
599
+
600
+ function showAnswerPopup(url) {
601
+ answerContent.innerHTML = '';
602
+ answerPopup.querySelector('.loading').style.display = 'block';
603
+ answerPopup.style.display = 'block';
604
+ if (answerCache[url]) {
605
+ displayAnswer(answerCache[url]);
606
+ } else {
607
+ const question = searchQueryInput.value;
608
+ fetchWebsiteAnswer(url, question).then(answer => {
609
+ answerCache[url] = answer;
610
+ displayAnswer(answer);
611
+ }).catch(error => {
612
+ console.error('Error fetching answer:', error);
613
+ displayAnswer('Error fetching answer.');
614
+ });
615
+ }
616
+ }
617
+
618
+ function displayAnswer(answer) {
619
+ answerPopup.querySelector('.loading').style.display = 'none';
620
+ answerContent.textContent = answer;
621
+ }
622
+
623
+ async function fetchWebsiteAnswer(url, question) {
624
+ const response = await fetch(`${BASE_URL}/api/ask_website?url=${url}&question=${encodeURIComponent(question)}(encodeURIComponent("Answer in concise way, First tell answer then Other thing"))&model=llama-3-70b`);
625
+ if (!response.ok) {
626
+ throw new Error('Error fetching answer from website.');
627
+ }
628
+ const data = await response.json();
629
+ return data[0] || 'No answer found.';
630
+ }
631
+
632
+ summaryPopup.querySelector('.close').addEventListener('click', () => {
633
+ summaryPopup.style.display = 'none';
634
+ });
635
+
636
+ answerPopup.querySelector('.close').addEventListener('click', () => {
637
+ answerPopup.style.display = 'none';
638
+ });
639
  </script>
640
  </body>
641
  </html>