Spaces:
Sleeping
Sleeping
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>DigiYatra Assistant</title> | |
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script> | |
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.3.2/uuid.min.js"></script> | |
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet"> | |
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet"> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/styles/atom-one-dark.min.css"> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js"></script> | |
<style> | |
/* Existing styles remain unchanged */ | |
:root { | |
--primary-color: #5853c0; | |
--secondary-color: #f0f8ff; | |
--text-color: #333; | |
--background-color: #f5f7fa; | |
} | |
body { | |
font-family: 'Poppins', sans-serif; | |
/* font-family: 'Roboto', sans-serif; */ | |
line-height: 1.6; | |
margin: 0; | |
padding: 0; | |
background-color: var(--background-color); | |
color: var(--text-color); | |
} | |
#app { | |
max-width: 900px; | |
margin: 0 auto; | |
padding: 10px; | |
} | |
.chat-container { | |
background-color: #ffffff; | |
border-radius: 15px; | |
box-shadow: 0 4px 20px rgba(0,0,0,0.1); | |
overflow: hidden; | |
display: flex; | |
flex-direction: column; | |
height: 98vh; | |
transition: all 0.3s ease; | |
position: relative; | |
} | |
.chat-header { | |
background-color: var(--primary-color); | |
color: #ffffff; | |
padding: 15px 20px; | |
font-size: 1.2em; | |
font-weight: 500; | |
position: absolute; | |
top: 0; | |
left: 0; | |
right: 0; | |
z-index: 10; | |
transition: transform 0.3s ease; | |
} | |
.messages { | |
flex-grow: 1; | |
overflow-y: auto; | |
padding: 20px; | |
display: flex; | |
flex-direction: column; | |
padding-top: 60px; | |
padding-bottom: 80px; | |
} | |
.message { | |
max-width: 80%; | |
margin-bottom: 20px; | |
padding: 15px 20px; | |
border-radius: 20px; | |
font-size: 16px; | |
line-height: 1.5; | |
word-wrap: break-word; | |
animation: fadeIn 0.5s ease; | |
} | |
@keyframes fadeIn { | |
from { opacity: 0; transform: translateY(10px); } | |
to { opacity: 1; transform: translateY(0); } | |
} | |
.user-message { | |
background-color: var(--primary-color); | |
color: #ffffff; | |
align-self: flex-end; | |
border-bottom-right-radius: 5px; | |
} | |
.bot-message { | |
background-color: var(--secondary-color); | |
color: var(--text-color); | |
align-self: flex-start; | |
border-bottom-left-radius: 5px; | |
} | |
.input-area { | |
display: flex; | |
padding: 15px; | |
background-color: #ffffff; | |
border-top: 1px solid #e0e0e0; | |
position: absolute; | |
bottom: 0; | |
left: 0; | |
right: 0; | |
z-index: 10; | |
transition: transform 0.3s ease; | |
} | |
#user-input { | |
flex-grow: 1; | |
padding: 12px 15px; | |
border: 2px solid var(--primary-color); | |
border-radius: 25px; | |
font-size: 16px; | |
outline: none; | |
transition: all 0.3s ease; | |
} | |
#user-input:focus { | |
box-shadow: 0 0 0 3px rgba(0,119,190,0.3); | |
} | |
.send-button, .reset-button { | |
background-color: var(--primary-color); | |
color: #ffffff; | |
border: none; | |
border-radius: 50%; | |
width: 50px; | |
height: 50px; | |
margin-left: 10px; | |
cursor: pointer; | |
display: flex; | |
align-items: center; | |
justify-content: center; | |
transition: all 0.3s ease; | |
} | |
.send-button:hover, .reset-button:hover { | |
background-color: #005fa3; | |
transform: scale(1.05); | |
} | |
.send-button svg, .reset-button svg { | |
width: 24px; | |
height: 24px; | |
} | |
.option-buttons { | |
display: flex; | |
flex-wrap: wrap; | |
gap: 10px; | |
margin-top: 15px; | |
} | |
.option-button { | |
background-color: #ffffff; | |
border: 2px solid var(--primary-color); | |
border-radius: 20px; | |
padding: 8px 16px; | |
font-size: 14px; | |
cursor: pointer; | |
transition: all 0.3s ease; | |
} | |
.option-button:hover { | |
background-color: var(--secondary-color); | |
transform: translateY(-2px); | |
} | |
.option-button.selected { | |
background-color: var(--primary-color); | |
color: #ffffff; | |
} | |
.audio-button { | |
background: none; | |
border: none; | |
cursor: pointer; | |
padding: 0; | |
margin-top: 10px; | |
transition: all 0.3s ease; | |
} | |
.audio-button:hover { | |
transform: scale(1.1); | |
} | |
.audio-button svg { | |
width: 30px; | |
height: 30px; | |
fill: var(--primary-color); | |
} | |
@media (max-width: 600px) { | |
#app { | |
padding: 10px; | |
} | |
.chat-container { | |
height: 95vh; | |
} | |
.message { | |
max-width: 90%; | |
} | |
} | |
.dot { | |
display: inline-block; | |
width: 8px; | |
height: 8px; | |
border-radius: 50%; | |
background-color: #5853c0; | |
margin: 0 3px; | |
animation: bounce 1.4s infinite ease-in-out; | |
} | |
.dot:nth-child(1) { animation-delay: -0.32s; } | |
.dot:nth-child(2) { animation-delay: -0.16s; } | |
@keyframes bounce { | |
0%, 80%, 100% { | |
transform: scale(0); | |
} 40% { | |
transform: scale(1.0); | |
} | |
} | |
.header-hidden { | |
transform: translateY(-100%); | |
} | |
.input-hidden { | |
transform: translateY(100%); | |
} | |
</style> | |
</head> | |
<body> | |
<div id="app"> | |
<div class="chat-container"> | |
<div class="chat-header" :class="{ 'header-hidden': isScrollingUp }">DigiYatra Assistant</div> | |
<div class="messages" ref="messageContainer" @scroll="handleScroll"> | |
<div v-for="(message, index) in messages" :key="index" | |
:class="['message', message.type === 'user' ? 'user-message' : 'bot-message']"> | |
<div v-if="message.type === 'bot' && message.content === ''" id="typing-animation"></div> | |
<div v-else v-html="message.content"></div> | |
<button v-if="message.type === 'bot' && message.audio" @click="toggleAudio(index)" class="audio-button"> | |
<svg v-if="!message.isPlaying" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> | |
<path d="M8 5v14l11-7z"/> | |
</svg> | |
<svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> | |
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/> | |
</svg> | |
</button> | |
</div> | |
</div> | |
<div class="input-area" :class="{ 'input-hidden': isScrollingUp }"> | |
<input type="text" id="user-input" v-model="userInput" @keyup.enter="sendMessage" placeholder="Type your message..."> | |
<button class="send-button" @click="sendMessage"> | |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> | |
<line x1="22" y1="2" x2="11" y2="13"></line> | |
<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon> | |
</svg> | |
</button> | |
<button class="reset-button" @click="resetConversation"> | |
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> | |
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"></path> | |
<path d="M3 3v5h5"></path> | |
</svg> | |
</button> | |
</div> | |
</div> | |
</div> | |
<script> | |
marked.setOptions({ | |
highlight: function (code, lang) { | |
if (lang && hljs.getLanguage(lang)) { | |
return hljs.highlight(code, { language: lang }).value; | |
} else { | |
return hljs.highlightAuto(code).value; | |
} | |
}, | |
sanitize: false | |
}); | |
function createTypingAnimation() { | |
const container = document.getElementById('typing-animation'); | |
container.innerHTML = ''; // Clear any existing dots | |
for (let i = 0; i < 3; i++) { | |
const dot = document.createElement('div'); | |
dot.className = 'dot'; | |
container.appendChild(dot); | |
} | |
} | |
const embedYouTube = (url) => { | |
let videoId; | |
const youtuBeMatch = url.match(/youtu\.be\/([^\?&]+)/); | |
const youtubeMatch = url.match(/youtube\.com\/watch\?v=([^\?&]+)/); | |
const embedMatch = url.match(/youtube\.com\/embed\/([^\?&]+)/); | |
if (youtuBeMatch) { | |
videoId = youtuBeMatch[1]; | |
} else if (youtubeMatch) { | |
videoId = youtubeMatch[1]; | |
} else if (embedMatch) { | |
videoId = embedMatch[1]; | |
} else { | |
// If the URL doesn't match known YouTube formats, return it unaltered | |
return url; | |
} | |
return ` | |
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;"> | |
<iframe | |
src="https://www.youtube.com/embed/${videoId}" | |
frameborder="0" | |
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" | |
allowfullscreen | |
style="position: absolute; top:0; left: 0; width: 100%; height: 100%;"> | |
</iframe> | |
</div> | |
`; | |
}; | |
const markdownLinkRegex = /\[([^\]]+)\]\((https?:\/\/(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/)[^\s)]+)\)/g; | |
const embedYouTubeInContent = (content) => { | |
return content.replace(markdownLinkRegex, (match, text, url) => { | |
return embedYouTube(url) || match; | |
}); | |
}; | |
const app = new Vue({ | |
el: '#app', | |
data: { | |
messages: [], | |
userInput: '', | |
selectedOptions: {}, | |
conversationId: '', | |
currentAudio: null, | |
isScrollingUp: false, | |
lastScrollTop: 0, | |
}, | |
methods: { | |
async sendMessage() { | |
if (!this.userInput.trim()) return; | |
this.messages.push({ type: 'user', content: marked.parse(this.userInput) }); | |
const message = this.userInput; | |
this.userInput = ''; | |
this.selectedOptions = {}; | |
let streamingIndex = this.messages.push({ type: 'bot', content: '' }) - 1; | |
this.$nextTick(() => { | |
createTypingAnimation(); | |
}); | |
try { | |
const response = await fetch('https://pvanand-rag-chat.hf.space/chat/', { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'X-API-Key': '44d5c2ac18ced6fc25c1e57dcd06fc0b31fb4ad97bf56e67540671a647465df4' | |
}, | |
body: JSON.stringify({ | |
query: message, | |
index_id: 'combined_digi_yatra', | |
model_id: 'openai/gpt-4o-mini', | |
conversation_id: this.conversationId, | |
user_id: 'string', | |
enable_followup: true | |
}) | |
}); | |
const reader = response.body.getReader(); | |
let rawResponse = ''; | |
let jsonData = null; | |
while (true) { | |
const { done, value } = await reader.read(); | |
if (done) break; | |
const chunk = new TextDecoder().decode(value); | |
if (chunk.includes('<json>')) { | |
const [textPart, jsonPart] = chunk.split('<json>'); | |
rawResponse += textPart; | |
jsonData = JSON.parse(jsonPart); | |
} else { | |
rawResponse += chunk; | |
} | |
// Clean up the raw response | |
rawResponse = rawResponse.replace(/<tools>[\s\S]*?<\/tools>/g, ''); | |
rawResponse = rawResponse.replace(/<interact>[\s\S]*?<\/interact>/g, ''); | |
rawResponse = rawResponse.replace(/<tool>[\s\S]*?<\/tool>/g, ''); | |
rawResponse = rawResponse.replace(/<\/?response>/g, ''); | |
console.log(rawResponse); | |
// Replace YouTube markdown links with embedded iframes | |
const parsedResponse = embedYouTubeInContent(rawResponse); | |
this.$set(this.messages[streamingIndex], 'content', marked.parse(parsedResponse)); | |
} | |
if (jsonData) { | |
this.renderClarificationQuestions(jsonData.clarification, streamingIndex); | |
} | |
const audioUrl = await this.convertToSpeech(rawResponse); | |
if (audioUrl) { | |
this.$set(this.messages[streamingIndex], 'audio', audioUrl); | |
} | |
} catch (error) { | |
console.error('Error:', error); | |
this.messages.push({ type: 'bot', content: 'An error occurred while processing your request.' }); | |
} | |
this.$nextTick(() => this.scrollToBottom()); | |
}, | |
handleScroll(event) { | |
const st = event.target.scrollTop; | |
this.isScrollingUp = st < this.lastScrollTop; | |
this.lastScrollTop = st <= 0 ? 0 : st; | |
}, | |
renderClarificationQuestions(clarification, messageIndex) { | |
if (!clarification || clarification.length === 0) return; | |
let clarificationHtml = ''; | |
clarification.forEach((item, questionIndex) => { | |
clarificationHtml += `<strong>${item.question}</strong><br>`; | |
clarificationHtml += '<div class="option-buttons">'; | |
item.options.forEach((option, optionIndex) => { | |
const escapedOption = option.replace(/'/g, "\\'"); | |
clarificationHtml += `<button class="option-button" onclick="app.toggleOption('${escapedOption}', ${questionIndex}, ${optionIndex})">${option}</button>`; | |
}); | |
clarificationHtml += '</div><br>'; | |
}); | |
this.$set(this.messages[messageIndex], 'content', this.messages[messageIndex].content + marked.parse(clarificationHtml)); | |
this.$nextTick(() => { | |
this.scrollToBottom(); | |
this.updateButtonStates(); | |
}); | |
}, | |
toggleOption(option, questionIndex, optionIndex) { | |
if (!this.selectedOptions[questionIndex]) { | |
this.$set(this.selectedOptions, questionIndex, []); | |
} | |
const index = this.selectedOptions[questionIndex].indexOf(option); | |
if (index > -1) { | |
this.selectedOptions[questionIndex].splice(index, 1); | |
} else { | |
this.selectedOptions[questionIndex].push(option); | |
} | |
this.updateInputFromSelectedOptions(); | |
this.updateButtonStates(); | |
}, | |
updateInputFromSelectedOptions() { | |
this.userInput = Object.entries(this.selectedOptions) | |
.map(([questionIndex, options]) => | |
`Q${parseInt(questionIndex) + 1}: ${options.join(', ')}`) | |
.join(' | '); | |
this.$nextTick(() => document.getElementById('user-input').focus()); | |
}, | |
updateButtonStates() { | |
Object.entries(this.selectedOptions).forEach(([questionIndex, options]) => { | |
const buttons = document.querySelectorAll(`.option-buttons:nth-of-type(${parseInt(questionIndex) + 1}) .option-button`); | |
buttons.forEach((button) => { | |
if (options.includes(button.textContent)) { | |
button.classList.add('selected'); | |
} else { | |
button.classList.remove('selected'); | |
} | |
}); | |
}); | |
}, | |
resetConversation() { | |
this.conversationId = uuid.v4(); | |
this.messages = [{ type: 'bot', content: 'How can I help you with DigiYatra?' }]; | |
this.selectedOptions = {}; | |
this.userInput = ''; | |
this.isScrollingUp = false; | |
this.lastScrollTop = 0; | |
// Reset scroll position | |
this.$nextTick(() => { | |
if (this.$refs.messageContainer) { | |
this.$refs.messageContainer.scrollTop = 0; | |
} | |
}); | |
// Ensure header and input area are visible | |
const header = document.querySelector('.chat-header'); | |
const inputArea = document.querySelector('.input-area'); | |
if (header) header.classList.remove('header-hidden'); | |
if (inputArea) inputArea.classList.remove('input-hidden'); | |
}, | |
scrollToBottom() { | |
const container = this.$refs.messageContainer; | |
container.scrollTop = container.scrollHeight; | |
}, | |
async convertToSpeech(text) { | |
const voice = 'en-US-JennyNeural'; | |
const encodedText = encodeURIComponent(text); | |
try { | |
const response = await fetch(`https://pvanand-audio-chat-indic.hf.space/auto-tts?text=${encodedText}`, { | |
method: 'GET', | |
headers: { | |
'accept': 'application/json' | |
} | |
}); | |
if (!response.ok) { | |
console.error(`TTS API error: ${response.status} ${response.statusText} INPUT TEXT:${text}`); | |
return null; // Return null if the API call fails | |
} | |
const blob = await response.blob(); | |
return URL.createObjectURL(blob); | |
} catch (error) { | |
console.error('Error in convertToSpeech:', error); | |
return null; // Return null if there's any error | |
} | |
}, | |
toggleAudio(index) { | |
const message = this.messages[index]; | |
if (this.currentAudio && this.currentAudio !== message.audioElement) { | |
this.currentAudio.pause(); | |
this.messages.forEach(m => { | |
if (m.audioElement === this.currentAudio) { | |
m.isPlaying = false; | |
} | |
}); | |
} | |
if (!message.audioElement) { | |
message.audioElement = new Audio(message.audio); | |
message.audioElement.addEventListener('ended', () => { | |
message.isPlaying = false; | |
this.$forceUpdate(); | |
}); | |
} | |
if (message.isPlaying) { | |
message.audioElement.pause(); | |
} else { | |
message.audioElement.play(); | |
this.currentAudio = message.audioElement; | |
} | |
message.isPlaying = !message.isPlaying; | |
this.$forceUpdate(); | |
} | |
}, | |
mounted() { | |
this.resetConversation(); | |
} | |
}); | |
</script> | |
</body> | |
</html> | |