Anupriya commited on
Commit ·
59fecf2
1
Parent(s): 16002bb
Added Chat stop method and image
Browse filesFiles changed (6)
12345678910115 unmodified lines171819202122232425262728293031323313 unmodified lines47484950515253545556575859606162637 unmodified lines71727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411422 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921018 unmodified lines2292302312322332342352362372382392402412422432442452462472482492 unmodified lines2522532542552562572582591 unmodified line2612622632642652662672682692703 unmodified lines2742752762772782792802812822832842852862872882892902912922932942952962972982993003013023036 unmodified lines3103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453461 unmodified line3483493503513523533543553563573583593603613623633643653663673683693703713726 unmodified lines3793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224233 unmodified lines42742842943043143243343443543643743843944044144244344444525 unmodified lines4714724734744754764773 unmodified lines4814824834844854864876 unmodified lines4944954964974984995006 unmodified lines5075085095105115125136 unmodified lines5205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695702 unmodified lines5735745755765775785795805815825835845855865875885895904 unmodified lines5955965975985996006018 unmodified lines6106116126136146156166176 unmodified lines6246256266276286296302 unmodified lines6336346356366376386396406416426436446456466476486496506516525 unmodified lines658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698/* Header Container Styling */.header-container {display: flex;justify-content: space-between;align-items: center;padding: 0vw 1vw;background-color: #03182d;/* background-color: #c19929;*/box-shadow: 0 0.4vw 0.8vw rgba(0, 0, 0, 0.2);width: 100%;position: sticky;5 unmodified linesmax-width: 5vw;height: auto;background: #e5e7eb;border-radius: 1vw;margin: 0.5vw;}.home-btn img {width: 5vw; /* Adjust the size of the home icon */}.home-btn img:hover {transform: scale(1.1); /* Slight zoom-in effect on hover */}h1 {font-size: 3vw;13 unmodified linesfont-display: swap;}/* Full-Screen Chat Container */.chat-container {display: flex;flex-direction: column;height: 100vh; /* Full viewport height */width: 100%; /* Full viewport width *//*background: linear-gradient(to bottom right, #fefefe, #f3f4f6);*/ /* Soft white-gray gradient */font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}.chat-bg {7 unmodified linesopacity: 0.2;}/*.chat-box {position: relative;}*//* Chat Header */.chat-header {text-align: center;background: linear-gradient(to right, #4ca1af, #6ac5cb); /* Modern purple-pink gradient */color: white;padding: 0px 0;font-size: 2.2rem;font-weight: bold;box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);flex-shrink: 0; /* Prevent shrinking */}.chat-box {display: flex;flex-direction: column;overflow-y: auto;height: calc(100vh - 180px); /* Adjust height as needed */padding: 2vw;background-color: rgba(35, 34, 32, 0.43);scroll-behavior: smooth; /* Smooth scrolling */flex-grow: 1;padding-bottom: 90px;}.input-box {display: flex;gap: 10px; /* Reduce gap between elements */padding: 8px; /* Reduce padding */background: #03182d; /* Blue background *//*background: #c19929;*/ /* Blue background */box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); /* Lighter shadow for a subtle effect */flex-shrink: 0;width: 100%;height: auto; /* Adjust height dynamically */min-height: 40px; /* Ensure it doesn't shrink too much */font-weight: bold;}.input-box textarea {flex: 1;height: auto; /* Automatically adjust height */max-height: 80px; /* Limit the maximum height */overflow-y: auto; /* Allow scrolling if needed */resize: none; /* Disable manual resizing */padding: 8px; /* Adjust padding for proper alignment */font-size: 1rem; /* Font size for input text */line-height: 1.2; /* Adjust line height for vertical centering */border: 1px solid rgb(93, 145, 195);border-radius: 8px; /* Smaller border radius */background: rgba(255, 255, 255, 0.04);color: white;outline: none;2 unmodified linesbox-sizing: border-box;}.input-box textarea:focus {border-color: rgb(135, 185, 235); /* Lighter shade of original color */box-shadow: 0 0 5px rgba(93, 145, 195, 0.6); /* Soft glow effect */text-align: left; /* Align text to the left */vertical-align: middle; /* This helps maintain proper alignment */line-height: normal; /* Ensures proper vertical centering */font-size: 1rem; /* Adjust font size if needed */color: white;font-weight: bold;}.input-box textarea::placeholder {text-align: left; /* Align text to the left */vertical-align: middle; /* This helps maintain proper alignment */line-height: normal; /* Ensures proper vertical centering */font-size: 1rem; /* Adjust font size if needed */color: rgba(255, 255, 255, 0.5); /* Subtle color for placeholder */}.input-box button {width: 55px; /* Fixed button size */height: 55px; /* Fixed button size */display: flex;align-items: center;justify-content: center;/*background: #a855f7;*/background: #5d91c3;border: none;border-radius: 8px;cursor: pointer;}.input-box button:hover {transform: scale(1.05);box-shadow: 0px 4px 10px rgba(14, 165, 233, 0.4); /* Subtle hover effect */}.button-icon {width: 34px; /* Default size for all icons */height: 34px;object-fit: contain;}.resume-icon {width: 40px; /* Slightly larger for balance */height: 40px;object-fit: contain;}.pause-icon {width: 31px; /* Custom size for pause icon */height: 31px;object-fit: contain;}18 unmodified lines}.suggestion-box li {padding: 8px 12px; /* Spacing inside each suggestion */cursor: pointer;font-size: 1rem;transition: background-color 0.3s ease;color: rgb(67 65 65); /* Text color */}.suggestion-box li:hover {background-color: rgba(0, 0, 0, 0.1); /* Subtle hover effect */border-radius: 4px; /* Rounded corners for hover */}.input-container {display: flex;flex-direction: column-reverse; /* Reverse order to place suggestions above input */position: relative;width: 100%;}2 unmodified linesdisplay: flex;gap: 10px;padding: 8px;background: #03182d; /* Background color of the input box *//*background: #c19929;*/ /* Background color of the input box */box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);flex-shrink: 0;width: 100%;1 unmodified linemin-height: 40px;}/* Glass Transparent Listening Indicator (Fully Centered) */.listening-box {position: fixed;top: 50%;3 unmodified linespadding: 45px;border-radius: 20px;width: 30vw;height: auto; /* Adjust height dynamically */min-height: 40vh; /* Ensure height remains balanced */box-shadow: 0px 8px 20px rgba(0, 0, 0, 0.15);backdrop-filter: blur(20px);-webkit-backdrop-filter: blur(20px);animation: fadeInScale 0.3s ease-in-out;display: flex;flex-direction: column;align-items: center; /* Ensure all elements stay centered */justify-content: center;border: 1px solid rgba(255, 255, 255, 0.2);text-align: center; /* Center text alignment */}/* Microphone Image (Centered Properly) */.microphone-image {width: 100px; /* Slightly bigger */height: 100px;display: block;margin: 0 auto 20px; /* Ensures it's centered with space below */animation: pulse 1.5s infinite alternate ease-in-out;}/* Pulse Effect */@keyframes pulse {from {transform: scale(1);6 unmodified lines}}/* Listening Text (Fully Centered) */.listening-box p {font-size: 15px; /* Increased size */color: black;font-weight: bold;text-align: center; /* Ensure it's aligned centrally */margin: 10px 0; /* Adjusted margin */text-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);margin-top: 3vw;}/* Mute & Close Buttons (Evenly Spaced & Centered) */.listening-actions {display: flex;justify-content: center; /* Ensure icons are centered */gap: 70px; /* More space between icons */margin-top: 65px;width: 100%;}/* Button Icons (Increased Size) */.mute-btn,.close-btn {background: rgba(255, 255, 255, 0.3);border: none;padding: 15px; /* Increased padding for larger buttons */border-radius: 50%;cursor: pointer;transition: transform 0.2s ease-in-out, background 0.3s;width: 75px; /* Increased button width */height: 75px; /* Increased button height */display: flex;align-items: center;justify-content: center;1 unmodified line-webkit-backdrop-filter: blur(12px);}/* Mute and Close Icon Styles (Proper Scaling) */.mute-btn img,.close-btn img {width: 50px; /* Bigger icons */height: 50px;}/* Hover Effects */.mute-btn:hover {background: rgba(255, 0, 0, 0.5); /* Red for mute */transform: scale(1.15);}.close-btn:hover {background: rgba(0, 0, 0, 0.5); /* Dark for close */transform: scale(1.15);}/* Fade-in with Scale Animation */@keyframes fadeInScale {from {opacity: 0;6 unmodified lines}}.error-text {color: black;background: #ffccccad; /* Light red */font-size: 2vw;font-weight: bold;text-align: center;padding: 8px 12px;border-radius: 5px;cursor: pointer;width: auto; /* Auto width based on text */margin-top: 10px; /* Space below buttons */display: inline-block; /* Single line */white-space: nowrap; /* Prevent text wrapping */transition: background 0.3s;}.error-text:hover {background: #ffaaaa; /* Slightly darker red on hover */}/* Popup Overlay */.popup-overlay {position: fixed;top: 0;left: 0;width: 100%;height: 100%;background: rgba(0, 0, 0, 0.5); /* Dark transparent background */display: flex;justify-content: center;align-items: center;z-index: 1000;}/* Popup Box */.popup-box {background: white;padding: 20px;3 unmodified linesbox-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);}/* Popup Title */.popup-box h3 {font-size: 18px;margin-bottom: 10px;}/* Popup Text */.popup-box p {font-size: 14px;color: #555;}/* Popup Button */.popup-button {background: #007bff;color: white;25 unmodified linesanimation: fadeIn 0.3s ease-in-out;}/* Typing dots animation */.typing-indicator span {width: 10px;height: 10px;3 unmodified linesanimation: typingDots 1.5s infinite ease-in-out;}/* Add animation delays for each dot */.typing-indicator span:nth-child(1) {animation-delay: 0s;}6 unmodified linesanimation-delay: 0.4s;}/* Keyframes for the typing dots */@keyframes typingDots {0%, 100% {transform: scale(0.8);6 unmodified lines}}/* Smooth fade-in effect */@keyframes fadeIn {from {opacity: 0;6 unmodified lines}}/* Container for hardcoded questions - Aligned left above the text field */.hardcoded-questions-container {display: flex;justify-content: flex-start; /* Align to the left */gap: 15px; /* Space between tabs */padding: 10px;background: rgba(255, 255, 255, 0.1); /* Subtle background */border-radius: 8px;margin-bottom: 5px; /* Space between questions and input box */flex-wrap: wrap; /* Allow wrapping on smaller screens */position: absolute;bottom: 60px; /* Adjust based on text field height */left: 10px; /* Align to the left side */width: auto; /* Adjust width dynamically */}/* Individual question tab */.hardcoded-question {padding: 10px 15px;background: rgba(200, 200, 200, 0.3); /* Light grey faded color */border-radius: 5px;font-size: 14px;font-weight: bold;cursor: pointer;transition: background 0.3s ease, transform 0.2s ease;white-space: nowrap; /* Prevent wrapping */border: 1px solid rgba(0, 0, 0, 0.2);}/* Hover effect */.hardcoded-question:hover {background: rgba(180, 180, 180, 0.5); /* Slightly darker grey on hover */transform: scale(1.05); /* Subtle pop effect */}/* Ensure responsiveness */@media (max-width: 600px) {.hardcoded-questions-container {width: 90%;bottom: 80px; /* Adjust spacing for smaller screens */left: 10px; /* Keep it left aligned */}.hardcoded-question {2 unmodified lines}}/* Message wrapper for each chat bubble */.message-wrapper {display: flex;align-items: flex-start;gap: 1vw;margin-bottom: 1vw; /* Space between each message */}/* Separate AI and user styles */.message-wrapper.user {flex-direction: row-reverse;text-align: right;4 unmodified linestext-align: left;}/* Profile Picture Styling */.profile-pic {width: 4vw;height: 4vw;8 unmodified linesobject-fit: cover;}/* Separate paragraph blocks */.ai .message {align-self: flex-start;background: #2b6296;6 unmodified linescolor: white;}/* Timestamp Styling */.message-timestamp {font-size: 0.8vw;color: rgba(255, 255, 255, 0.8);2 unmodified linestext-align: right;}.paragraph-block {background: #2b6296;color: white;padding: 1vw;border-radius: 1vw;margin-bottom: 0.5vw; /* ✅ Adjusted for better spacing */box-shadow: 0 0.3vw 0.8vw rgba(0, 0, 0, 0.1);line-height: 1.5;max-width: 48vw;}/* Normal messages remain in a single block */.message {max-width: 50vw;padding: 1vw 2vw;5 unmodified linescolor: white;}.structured-response {background: #2b6296;color: white;padding: 1vw;border-radius: 1vw;margin-bottom: 0.3vw; /* ✅ Reduced spacing */box-shadow: 0 0.3vw 0.8vw rgba(0, 0, 0, 0.1);line-height: 1.4; /* ✅ Adjusted line height */max-width: 48vw;word-break: break-word;}/* ✅ Reduce space between numbered and bulleted list items */.structured-response b {display: inline-block;margin-top: 0.3vw; /* ✅ Reduced margin for numbers */}.structured-response br {display: block;content: "";margin: 0.2vw 0; /* ✅ Reduce line spacing */}/* ✅ Ensure numbered and bulleted lists have proper spacing */.structured-response ul,.structured-response ol {padding-left: 1.2vw; /* ✅ Slightly reduced indentation */margin-bottom: 0; /* ✅ Remove extra bottom margin */}.structured-response ul li,.structured-response ol li {margin-bottom: 0.2vw; /* ✅ Reduced space between list items */line-height: 1.4;}1234567895 unmodified lines151617181920212223242526272829303113 unmodified lines4546474849505152535455567 unmodified lines6465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151162 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317418 unmodified lines1931941951961971981992002012022032042052062072082092102112122132 unmodified lines2162172182192202212221 unmodified line2242252262272282293 unmodified lines2332342352362372382392402412422432442452462472482492502512522532542552562572582592606 unmodified lines2672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993001 unmodified line3023033043053063073083093103113123133143153163173183193203213223236 unmodified lines3303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683 unmodified lines37237337437537637737837938038138238338438538638725 unmodified lines4134144154164174183 unmodified lines4224234244254264276 unmodified lines4344354364374384396 unmodified lines4464474484494504516 unmodified lines4584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995002 unmodified lines5035045055065075085095105115125135145154 unmodified lines5205215225235245258 unmodified lines5345355365375385396 unmodified lines5465475485495505512 unmodified lines5545555565575585595605615625635645655665675685695705 unmodified lines576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612.header-container {display: flex;justify-content: space-between;align-items: center;padding: 0vw 1vw;background-color: #03182d;box-shadow: 0 0.4vw 0.8vw rgba(0, 0, 0, 0.2);width: 100%;position: sticky;5 unmodified linesmax-width: 5vw;height: auto;background: #e5e7eb;border-radius: 50%;margin: 0.5vw;}.home-btn img {width: 5vw;}.home-btn img:hover {transform: scale(1.1);}h1 {font-size: 3vw;13 unmodified linesfont-display: swap;}.chat-container {display: flex;flex-direction: column;height: 100vh;width: 100%;font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}.chat-bg {7 unmodified linesopacity: 0.2;}.chat-header {text-align: center;background: linear-gradient(to right, #4ca1af, #6ac5cb);color: white;padding: 0px 0;font-size: 2.2rem;font-weight: bold;box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);flex-shrink: 0;}.chat-box {display: flex;flex-direction: column;overflow-y: auto;height: calc(100vh - 180px);padding: 2vw;background-color: rgba(35, 34, 32, 0.43);scroll-behavior: smooth;flex-grow: 1;padding-bottom: 90px;}.input-box {display: flex;gap: 10px;padding: 8px;background: #03182d;box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);flex-shrink: 0;width: 100%;height: auto;min-height: 40px;font-weight: bold;}.input-box textarea {flex: 1;height: auto;max-height: 80px;overflow-y: auto;resize: none;padding: 8px;font-size: 1rem;line-height: 1.2;border: 1px solid rgb(93, 145, 195);border-radius: 8px;background: rgba(255, 255, 255, 0.04);color: white;outline: none;2 unmodified linesbox-sizing: border-box;}.input-box textarea:focus {border-color: rgb(135, 185, 235);box-shadow: 0 0 5px rgba(93, 145, 195, 0.6);text-align: left;vertical-align: middle;line-height: normal;font-size: 1rem;color: white;font-weight: bold;}.input-box textarea::placeholder {text-align: left;vertical-align: middle;line-height: normal;font-size: 1rem;color: rgba(255, 255, 255, 0.5);}.input-box button {width: 55px;height: 55px;display: flex;align-items: center;justify-content: center;background: #5d91c3;border: none;border-radius: 8px;cursor: pointer;}.input-box button:hover {transform: scale(1.05);box-shadow: 0px 4px 10px rgba(14, 165, 233, 0.4);}.button-icon {width: 34px;height: 34px;object-fit: contain;}.resume-icon {width: 40px;height: 40px;object-fit: contain;}.pause-icon {width: 31px;height: 31px;object-fit: contain;}18 unmodified lines}.suggestion-box li {padding: 8px 12px;cursor: pointer;font-size: 1rem;transition: background-color 0.3s ease;color: rgb(67 65 65);}.suggestion-box li:hover {background-color: rgba(0, 0, 0, 0.1);border-radius: 4px;}.input-container {display: flex;flex-direction: column-reverse;position: relative;width: 100%;}2 unmodified linesdisplay: flex;gap: 10px;padding: 8px;background: #03182d;box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);flex-shrink: 0;width: 100%;1 unmodified linemin-height: 40px;}.listening-box {position: fixed;top: 50%;3 unmodified linespadding: 45px;border-radius: 20px;width: 30vw;height: auto;min-height: 40vh;box-shadow: 0px 8px 20px rgba(0, 0, 0, 0.15);backdrop-filter: blur(20px);-webkit-backdrop-filter: blur(20px);animation: fadeInScale 0.3s ease-in-out;display: flex;flex-direction: column;align-items: center;justify-content: center;border: 1px solid rgba(255, 255, 255, 0.2);text-align: center;}.microphone-image {width: 100px;height: 100px;display: block;margin: 0 auto 20px;animation: pulse 1.5s infinite alternate ease-in-out;}@keyframes pulse {from {transform: scale(1);6 unmodified lines}}.listening-box p {font-size: 15px;color: black;font-weight: bold;text-align: center;margin: 10px 0;text-shadow: 0px 0px 8px rgba(0, 0, 0, 0.3);margin-top: 3vw;}.listening-actions {display: flex;justify-content: center;gap: 70px;margin-top: 65px;width: 100%;}.mute-btn,.close-btn {background: rgba(255, 255, 255, 0.3);border: none;padding: 15px;border-radius: 50%;cursor: pointer;transition: transform 0.2s ease-in-out, background 0.3s;width: 75px;height: 75px;display: flex;align-items: center;justify-content: center;1 unmodified line-webkit-backdrop-filter: blur(12px);}.mute-btn img,.close-btn img {width: 50px;height: 50px;}.mute-btn:hover {background: rgba(255, 0, 0, 0.5);transform: scale(1.15);}.close-btn:hover {background: rgba(0, 0, 0, 0.5);transform: scale(1.15);}@keyframes fadeInScale {from {opacity: 0;6 unmodified lines}}.error-text {color: black;background: #ffccccad;font-size: 2vw;font-weight: bold;text-align: center;padding: 8px 12px;border-radius: 5px;cursor: pointer;width: auto;margin-top: 10px;display: inline-block;white-space: nowrap;transition: background 0.3s;}.error-text:hover {background: #ffaaaa;}.popup-overlay {position: fixed;top: 0;left: 0;width: 100%;height: 100%;background: rgba(0, 0, 0, 0.5);display: flex;justify-content: center;align-items: center;z-index: 1000;}.popup-box {background: white;padding: 20px;3 unmodified linesbox-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);}.popup-box h3 {font-size: 18px;margin-bottom: 10px;}.popup-box p {font-size: 14px;color: #555;}.popup-button {background: #007bff;color: white;25 unmodified linesanimation: fadeIn 0.3s ease-in-out;}.typing-indicator span {width: 10px;height: 10px;3 unmodified linesanimation: typingDots 1.5s infinite ease-in-out;}.typing-indicator span:nth-child(1) {animation-delay: 0s;}6 unmodified linesanimation-delay: 0.4s;}@keyframes typingDots {0%, 100% {transform: scale(0.8);6 unmodified lines}}@keyframes fadeIn {from {opacity: 0;6 unmodified lines}}.hardcoded-questions-container {display: flex;justify-content: flex-start;gap: 15px;padding: 10px;background: rgba(255, 255, 255, 0.1);border-radius: 8px;margin-bottom: 5px;flex-wrap: wrap;position: absolute;bottom: 60px;left: 10px;width: auto;}.hardcoded-question {padding: 10px 15px;background: rgba(200, 200, 200, 0.3);border-radius: 5px;font-size: 14px;font-weight: bold;cursor: pointer;transition: background 0.3s ease, transform 0.2s ease;white-space: nowrap;border: 1px solid rgba(0, 0, 0, 0.2);}.hardcoded-question:hover {background: rgba(180, 180, 180, 0.5);transform: scale(1.05);}@media (max-width: 600px) {.hardcoded-questions-container {width: 90%;bottom: 80px;left: 10px;}.hardcoded-question {2 unmodified lines}}.message-wrapper {display: flex;align-items: flex-start;gap: 1vw;margin-bottom: 1vw;}.message-wrapper.user {flex-direction: row-reverse;text-align: right;4 unmodified linestext-align: left;}.profile-pic {width: 4vw;height: 4vw;8 unmodified linesobject-fit: cover;}.ai .message {align-self: flex-start;background: #2b6296;6 unmodified linescolor: white;}.message-timestamp {font-size: 0.8vw;color: rgba(255, 255, 255, 0.8);2 unmodified linestext-align: right;}.paragraph-block {background: #2b6296;color: white;padding: 1vw;border-radius: 1vw;margin-bottom: 0.5vw;box-shadow: 0 0.3vw 0.8vw rgba(0, 0, 0, 0.1);line-height: 1.5;max-width: 48vw;}.message {max-width: 50vw;padding: 1vw 2vw;5 unmodified linescolor: white;}.structured-response {background: #2b6296;color: white;padding: 1vw;border-radius: 1vw;margin-bottom: 0.3vw;box-shadow: 0 0.3vw 0.8vw rgba(0, 0, 0, 0.1);line-height: 1.4;max-width: 48vw;word-break: break-word;}.structured-response b {display: inline-block;margin-top: 0.3vw;}.structured-response br {display: block;content: "";margin: 0.2vw 0;}.structured-response ul,.structured-response ol {padding-left: 1.2vw;margin-bottom: 0;}.structured-response ul li,.structured-response ol li {margin-bottom: 0.2vw;line-height: 1.4;}
123456788 unmodified lines171819202122232425262728293031323334353 unmodified lines39404142434445463 unmodified lines5051525354555657585960616263646566676869707172731 unmodified line75767778798081828384858687888990911 unmodified line939495969798991001011021031041051062 unmodified lines1091101111121131141151161171181191201211222 unmodified lines125126127128<div class="chat-container"><div class="header-container"><div class="logo"><a (click)="goToHome()" routerLink="/home" class="brand-link"><img src="assets/images/pykara-logo.png" alt="Pykara Logo" />8 unmodified lines<img src="assets/images/home.png" alt="Home" class="home-icon" /></a></div></div><div class="chat-box" #chatBox><img src="assets/images/chat/chatbg.png" alt="Chat Background" class="chat-bg" /><div *ngFor="let message of messages"><!-- User Messages --><div *ngIf="message.from === 'user'" class="message-wrapper user"><div class="profile-pic"><img src="assets/images/chat/rabbit.png" alt="User Profile Picture" />3 unmodified lines<div class="message-timestamp">{{ message.timestamp }}</div></div></div><!-- AI Messages --><div *ngIf="message.from === 'ai'" class="message-wrapper ai"><div class="profile-pic"><img src="assets/images/chat/lion.png" alt="AI Profile Picture" />3 unmodified lines<div class="message-timestamp">{{ message.timestamp }}</div></div></div></div><!-- AI typing indicator --><div *ngIf="isTyping" class="typing-indicator">AI is typing<span></span><span></span><span></span></div></div><div class="input-container"><div class="input-box"><textarea [(ngModel)]="userInput"(focus)="showHardcodedQuestions()"1 unmodified line(input)="adjustTextareaHeight($event); getSuggestions()"(keydown)="handleEnterPress($event)"placeholder="Type your message here..."[disabled]="isSpeaking"></textarea><button (click)="isSpeaking ? (isAudioPaused ? resumeAudio() : pauseAudio()) : handleButtonClick()"><img [src]="isSpeaking ? (isAudioPaused ? 'assets/images/chat/resume-icon.png' : 'assets/images/chat/pause-icon.png') : getButtonIcon()"alt="Button Icon"class="button-icon" /></button></div><!-- Hardcoded questions (Shown only when focused) --><div class="hardcoded-questions-container" *ngIf="showQuestions"><div class="hardcoded-question" (click)="selectHardcodedQuestion('What is grammar?')">What is grammar?</div><div class="hardcoded-question" (click)="selectHardcodedQuestion('What are the rules to be followed in grammar?')">What are the rules to be followed in grammar?</div>1 unmodified line<div class="hardcoded-question" (click)="selectHardcodedQuestion('Why do we need to follow grammar rules while writing and speaking?')">Why do we need to follow grammar rules while writing and speaking?</div><div class="hardcoded-question" (click)="selectHardcodedQuestion('How do you identify a subject and a predicate in a sentence?')">How do you identify a subject and a predicate in a sentence?</div></div></div><!-- Listening Box --><div class="listening-box" *ngIf="isListening"><div class="listening-content"><img src="assets/images/chat/microphone-icon.png" alt="Microphone" class="microphone-image" /><p *ngIf="!errorMessage">Listening...</p><div class="listening-actions"><button class="mute-btn" (click)="muteMicrophone()"><img src="assets/images/chat/mic.png" alt="Mute" />2 unmodified lines<img src="assets/images/chat/cross.png" alt="Close" /></button></div><p *ngIf="errorMessage" class="error-text" (click)="openMicrophoneSettings()">{{ errorMessage }}</p></div></div><!-- Microphone Access Popup --><div class="popup-overlay" *ngIf="showMicPopup"><div class="popup-box"><h3>Microphone access required</h3>2 unmodified lines</div></div></div>123458 unmodified lines14151617181920212223243 unmodified lines2829303132333 unmodified lines373839404142434445464748495051521 unmodified line545556575859606162636465666768691 unmodified line7172737475767778798081822 unmodified lines858687888990919293942 unmodified lines979899<div class="chat-container"><header class="header-container"><div class="logo"><a (click)="goToHome()" routerLink="/home" class="brand-link"><img src="assets/images/pykara-logo.png" alt="Pykara Logo" />8 unmodified lines<img src="assets/images/home.png" alt="Home" class="home-icon" /></a></div></header><main class="chat-box" #chatBox><img src="assets/images/chat/chatbg.png" alt="Chat Background" class="chat-bg" /><ng-container *ngFor="let message of messages"><div *ngIf="message.from === 'user'" class="message-wrapper user"><div class="profile-pic"><img src="assets/images/chat/rabbit.png" alt="User Profile Picture" />3 unmodified lines<div class="message-timestamp">{{ message.timestamp }}</div></div></div><div *ngIf="message.from === 'ai'" class="message-wrapper ai"><div class="profile-pic"><img src="assets/images/chat/lion.png" alt="AI Profile Picture" />3 unmodified lines<div class="message-timestamp">{{ message.timestamp }}</div></div></div></ng-container><div *ngIf="isTyping" class="typing-indicator" role="status" aria-live="polite">AI is typing<span></span><span></span><span></span></div></main><section class="input-container"><div class="input-box"><textarea [(ngModel)]="userInput"(focus)="showHardcodedQuestions()"1 unmodified line(input)="adjustTextareaHeight($event); getSuggestions()"(keydown)="handleEnterPress($event)"placeholder="Type your message here..."[disabled]="isSpeaking"aria-label="Message input"></textarea><button (click)="isSpeaking ? stopSpeaking() : handleButtonClick()"[disabled]="isSubmitting"aria-label="Send or voice"><img [src]="isSpeaking ? 'assets/images/chat/stop.png' : getButtonIcon()"alt="Action"class="button-icon" /></button></div><div class="hardcoded-questions-container" *ngIf="showQuestions"><div class="hardcoded-question" (click)="selectHardcodedQuestion('What is grammar?')">What is grammar?</div><div class="hardcoded-question" (click)="selectHardcodedQuestion('What are the rules to be followed in grammar?')">What are the rules to be followed in grammar?</div>1 unmodified line<div class="hardcoded-question" (click)="selectHardcodedQuestion('Why do we need to follow grammar rules while writing and speaking?')">Why do we need to follow grammar rules while writing and speaking?</div><div class="hardcoded-question" (click)="selectHardcodedQuestion('How do you identify a subject and a predicate in a sentence?')">How do you identify a subject and a predicate in a sentence?</div></div></section><div class="listening-box" *ngIf="isListening" role="dialog" aria-modal="true"><div class="listening-content"><img src="assets/images/chat/microphone-icon.png" alt="Microphone" class="microphone-image" /><p *ngIf="!errorMessage">Listening...</p><div class="listening-actions"><button class="mute-btn" (click)="muteMicrophone()"><img src="assets/images/chat/mic.png" alt="Mute" />2 unmodified lines<img src="assets/images/chat/cross.png" alt="Close" /></button></div><p *ngIf="errorMessage" class="error-text" (click)="openMicrophoneSettings()">{{ errorMessage }}</p></div></div><div class="popup-overlay" *ngIf="showMicPopup"><div class="popup-box"><h3>Microphone access required</h3>2 unmodified lines</div></div></div>
12345678910111213143 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656 unmodified lines727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131146 unmodified lines1211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601612 unmodified lines1641651661671681691701715 unmodified lines1771781791801811821831841851861871881891901911921931941952 unmodified lines1981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672 unmodified lines2702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053 unmodified lines3093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483491 unmodified line3513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833842 unmodified lines3873883893903913923931 unmodified line3953963973983994004014024034044054064074084092 unmodified lines4124134144154164174184194204214224234244254264274284294304314324334344353 unmodified lines43944044144244344444544644744844945045145245345445545645745845946046146246346446546646746819 unmodified lines4884894904914924934942 unmodified lines4974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805813 unmodified lines58558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864911 unmodified lines661662663664665666667import { Component, Inject, OnDestroy, PLATFORM_ID, ChangeDetectorRef } from '@angular/core';import { ApiService } from './api.service'; // Import ApiServiceimport { FormsModule } from '@angular/forms'; // Import FormsModule for two-way bindingimport { CommonModule } from '@angular/common';import { Router, RouterModule } from '@angular/router';import { isPlatformBrowser } from '@angular/common';import { ViewChild, ElementRef } from '@angular/core';import { Renderer2 } from '@angular/core';@Component({selector: 'app-chat',3 unmodified linesstyleUrl: './chat.component.css'})export class ChatComponent implements OnDestroy {showQuestions: boolean = false; // Flag to show hardcoded questionsuserInput: string = '';messages: { from: string, text: string, timestamp: string; isPlaying?: boolean }[] = [];isTyping: boolean = false; // Typing indicator@ViewChild('chatBox') chatBox!: ElementRef;isLoadingSpeech: boolean = false; // ✅ Add this line to fix the errorselectedVoice: SpeechSynthesisVoice | null = null;errorMessage: string = "";recognition: any; // SpeechRecognition objectspeechSynthesisInstance: SpeechSynthesisUtterance | null = null;isListening: boolean = false;isProcessingSpeech: boolean = false; // Flag to prevent duplicate processing// isVoiceInput: boolean = false; // Indicates if the input is from voiceisSpeaking: boolean = false; // Track if text-to-speech is ongoingisAudioPaused: boolean = false; // Indicates if the audio is pausedisInputValid: boolean = false;suggestions: string[] = []; // Holds suggested grammar questionsshowMicPopup: boolean = false;ngAfterViewChecked() {// Adding a delay for smooth scrollingsetTimeout(() => {this.scrollToBottom();}, 100); // Adjust the timeout if necessary}// Function to scroll to the bottom of the chatprivate scrollToBottom(): void {try {this.chatBox.nativeElement.scrollTop = this.chatBox.nativeElement.scrollHeight;} catch (err) { }}constructor(private apiService: ApiService, private cdr: ChangeDetectorRef, @Inject(PLATFORM_ID,) private platformId: object, private router: Router, private renderer: Renderer2) {window.speechSynthesis.onvoiceschanged = () => {console.log("Available Voices:", window.speechSynthesis.getVoices());};// Initialize SpeechRecognition if supportedif (isPlatformBrowser(this.platformId)) {const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;if (SpeechRecognition) {6 unmodified linesif (event.results && event.results[0]) {const transcript = event.results[0][0].transcript.trim();console.log('Recognized speech:', transcript);this.userInput = transcript; // Set the recognized speech as inputthis.sendMessage(); // Automatically send the message after recognition// Stop recognition to prevent multiple triggersthis.recognition.stop();this.isListening = false; // Hide the overlay}};this.recognition.onerror = (event: any) => {console.error('Speech Recognition Error:', event.error);this.isProcessingSpeech = false; // Reset the flag on error};} else {console.warn('Speech Recognition is not supported in this browser.');}// Add beforeunload listener to stop audio on page refresh or unloadwindow.addEventListener('beforeunload', this.handleUnload);}}// Handle page unload to stop audioprivate handleUnload = (): void => {if (window.speechSynthesis) {window.speechSynthesis.cancel();}};// Lifecycle hook to clean up resourcesngOnDestroy(): void {if (isPlatformBrowser(this.platformId)) {if (window.speechSynthesis) {window.speechSynthesis.cancel();}// Remove the unload event listenerwindow.removeEventListener('beforeunload', this.handleUnload);}}6 unmodified linesthis.showMicPopup = false;}// Show hardcoded questions when user focuses on inputshowHardcodedQuestions(): void {setTimeout(() => {this.showQuestions = true;}, 100); // Small delay to prevent blur from closing it immediately}// Hide hardcoded questions when user clicks outsidehideHardcodedQuestions(): void {setTimeout(() => {this.showQuestions = false;}, 200); // Allow time for click event to register}selectHardcodedQuestion(question: string): void {this.userInput = question; // Set the selected questionthis.showQuestions = false; // Hide the hardcoded questionssetTimeout(() => {this.sendMessage(); // Send the selected questionthis.userInput = ''; // Clear the text field after sending}, 100); // Small delay to ensure UI updates before clearing}getSuggestions(): void {if (!this.userInput || this.userInput.trim().length < 1 || this.isSpeaking) {this.suggestions = []; // Clear suggestions if no input or AI is speakingreturn;}2 unmodified linesconsole.log("API Response:", response);if (response.suggestions) {this.suggestions = response.suggestions.filter((s: string) => s && s.trim().length > 0) // Remove empty suggestions.map((s: string) => s.replace(/^\d+\.\s*/, "")); // Remove numbering} else {this.suggestions = [];}5 unmodified lines);}// When a user selects a suggestion, send it as a messageselectSuggestion(suggestion: string): void {this.userInput = suggestion;this.suggestions = []; // Clear suggestions after selectionthis.sendMessage(); // Send the selected suggestion}sendMessage(inputText?: string): void {const message = inputText ? inputText.trim() : this.userInput.trim();if (!message) {2 unmodified lineslet sessionId = localStorage.getItem('session_id');// ✅ Add user message to chatthis.messages.push({ from: 'user', text: message, timestamp: new Date().toLocaleTimeString() });this.userInput = ''; // ✅ Clear input field after sendingthis.isTyping = true;this.cdr.detectChanges();this.scrollToBottom(); // ✅ Scroll after adding user messagethis.apiService.askQuestion(message, sessionId).subscribe((response) => {this.isTyping = false;let explanation = response?.response || 'No explanation available.';if (response.session_id && !sessionId) {localStorage.setItem('session_id', response.session_id);}let formattedExplanation = explanation.trim().split('\n').map((para: string) => para.trim()).join('\n');this.messages.push({ from: 'ai', text: formattedExplanation, timestamp: new Date().toLocaleTimeString() });this.cdr.detectChanges();this.scrollToBottom(); // ✅ Scroll after AI responsethis.speakResponse(explanation);},(error) => {this.isTyping = false;const errorMessage = 'Error: Could not get a response from the server.';console.error("API Error:", error);this.messages.push({ from: 'ai', text: errorMessage, timestamp: new Date().toLocaleTimeString() });this.cdr.detectChanges();this.scrollToBottom(); // ✅ Scroll even if an error occursthis.speakResponse(errorMessage);});}formatStructuredResponse(text: string): string {let formattedText = text.replace(/\n/g, '<br>') // Preserve line breaks.replace(/(\d+)\.\s/g, '<b>$1.</b> ') // Bold numbered lists.replace(/\•\s/g, '✔️ ') // Replace bullets with custom emojis.replace(/\-\s/g, '🔹 ') // Replace hyphen bullets with emoji.replace(/(\*\*)(.*?)\1/g, '<b>$2</b>'); // Convert "**bold text**" to <b>bold text</b>return formattedText;}speakResponse(responseText: string): void {if (!responseText) {console.warn('No response text provided for speech.');2 unmodified linesconsole.log('Initiating text-to-speech with response:', responseText);// Find the last AI message and update it dynamicallylet lastAiMessage = this.messages.slice().reverse().find((msg) => msg.from === 'ai');if (!lastAiMessage) {// If no AI message exists, create onelastAiMessage = { from: 'ai', text: '', timestamp: new Date().toLocaleTimeString() };this.messages.push(lastAiMessage);} else {// Clear existing text before speakinglastAiMessage.text = '';}this.cdr.detectChanges(); // Ensure UI updates immediately// Split response text into words for live updatesconst words = responseText.split(' ');let currentWordIndex = 0;// Create SpeechSynthesisUtteranceconst speech = new SpeechSynthesisUtterance();speech.text = responseText;speech.lang = 'en-US';speech.pitch = 1; // Adjust pitch (higher values sound more feminine)speech.rate = 1; // Normal speaking speedthis.isSpeaking = true;// Fetch available voicesconst voices = window.speechSynthesis.getVoices();// ✅ Use Microsoft Zira for a female voicelet femaleVoice = voices.find(voice => voice.name === "Microsoft Zira - English (United States)");if (femaleVoice) {3 unmodified linesconsole.warn("Microsoft Zira not found, using default.");}// Update AI response dynamically as words are spokenspeech.onboundary = (event) => {if (event.name === 'word' && currentWordIndex < words.length) {lastAiMessage!.text = words.slice(0, currentWordIndex + 1).join(' '); // Update text word by wordcurrentWordIndex++;this.cdr.detectChanges(); // Update UI dynamically}};// When speech ends, keep the full response or leave the last wordspeech.onend = () => {console.log('Speech ended.');this.isSpeaking = false;lastAiMessage!.text = responseText; // Show full response after speech endsthis.cdr.detectChanges();};// Start speakingconsole.log('Starting speech synthesis...');window.speechSynthesis.speak(speech);}ngOnInit(): void {if (window.speechSynthesis.onvoiceschanged !== undefined) {window.speechSynthesis.onvoiceschanged = () => {1 unmodified line};}// Load voices immediately in case they are already availablethis.loadVoices();}loadVoices(): void {const voices = window.speechSynthesis.getVoices();if (!voices.length) {console.warn("No voices available yet, retrying...");setTimeout(() => this.loadVoices(), 500); // Retry loading voicesreturn;}console.log("Available Voices:", voices.map(v => v.name)); // Debugging// ✅ Preferred female voicesconst preferredVoices = ["Google UK English Female","Google US English Female","Microsoft Zira - English (United States)", // Edge/Windows"Microsoft Hazel - English (United Kingdom)","Google en-GB Female","Google en-US Female"];// Try to find a preferred female voicefor (let voiceName of preferredVoices) {const foundVoice = voices.find(voice => voice.name === voiceName);if (foundVoice) {2 unmodified lines}}// If no preferred female voice found, pick any available female voiceif (!this.selectedVoice) {this.selectedVoice = voices.find(voice => voice.name.toLowerCase().includes("female")) || voices[0];}1 unmodified lineconsole.log("Selected AI Voice:", this.selectedVoice?.name);}pauseAudio(): void {if (window.speechSynthesis.speaking && !window.speechSynthesis.paused) {window.speechSynthesis.pause();this.isAudioPaused = true;console.log('AI Speech Paused');this.cdr.detectChanges(); // Update UI}}2 unmodified lineswindow.speechSynthesis.resume();this.isAudioPaused = false;console.log('AI Speech Resumed');this.cdr.detectChanges(); // Update UI}}muteMicrophone(): void {console.log("Microphone muted");// Logic to mute the microphone}// Start listening for voice inputstartListening(): void {this.isListening = true; // Show the overlaythis.isProcessingSpeech = false; // Reset the flag before startingif (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {navigator.mediaDevices3 unmodified linesconsole.log('Starting speech recognition...');this.recognition.start();// Debugging eventsthis.recognition.onaudiostart = () => console.log('Audio capturing started.');this.recognition.onspeechstart = () => console.log('Speech has been detected.');this.recognition.onspeechend = () => console.log('Speech ended, processing...');this.recognition.onaudioend = () => console.log('Audio capturing ended.');// Automatically process recognized speechthis.recognition.onresult = (event: any) => {if (event.results && event.results[0]) {const transcript = event.results[0][0].transcript.trim();console.log('Recognized speech:', transcript);// Set the recognized speech as inputthis.userInput = transcript;// Automatically send the messageif (this.userInput.trim()) {console.log('Sending question automatically:', this.userInput);this.sendMessage(); // Call sendMessage to process the question}// Stop recognition to prevent multiple triggersthis.recognition.stop();this.isListening = false; // Hide the overlay}};19 unmodified lines.catch((error) => {console.error('Microphone access denied:', error);this.errorMessage = 'Please enable microphone access to use this feature.';this.isListening = true; // Keep the overlay visible});} else {2 unmodified lines}stopListening(): void {this.isListening = false; // Hide the overlayif (this.recognition) {this.recognition.stop(); // Stop speech recognition}}// Toggle between play and pause for a specific messagetoggleAudio(message: { text: string, isPlaying?: boolean }): void {if (this.speechSynthesisInstance && this.speechSynthesisInstance.text === message.text) {if (message.isPlaying) {// Pause the currently playing audiowindow.speechSynthesis.pause();message.isPlaying = false;} else {// Resume the paused audiowindow.speechSynthesis.resume();message.isPlaying = true;}} else {// Stop any currently playing audioif (this.speechSynthesisInstance) {window.speechSynthesis.cancel();}this.messages.forEach((msg) => (msg.isPlaying = false)); // Reset all states// Start playback for the selected messagemessage.isPlaying = true;this.speechSynthesisInstance = new SpeechSynthesisUtterance(message.text);this.speechSynthesisInstance.lang = 'en-US';this.speechSynthesisInstance.pitch = 1;this.speechSynthesisInstance.rate = 1;// When playback ends, reset the statethis.speechSynthesisInstance.onend = () => {message.isPlaying = false;this.speechSynthesisInstance = null;};// Play the audiowindow.speechSynthesis.speak(this.speechSynthesisInstance);}}goToHome() {this.router.navigate(['/home']);}copySuccessIndex: number | null = null; // Track copied message indexcopyToClipboard(text: string, index: number): void {navigator.clipboard.writeText(text).then(() => {this.copySuccessIndex = index; // Show tick icon for copied messagesetTimeout(() => {this.copySuccessIndex = null; // Hide tick after 2 seconds}, 2000);}).catch(err => {console.error('Failed to copy: ', err);});}// Function to check input validitycheckInput() {this.isInputValid = this.userInput.trim().length > 0;}handleButtonClick(): void {if (this.userInput.trim().length > 0) {this.showQuestions = false; // Hide tabs when user manually enters textconst messageToSend = this.userInput; // Store input before clearingthis.userInput = ''; // Clear input for UI updatethis.sendMessage(messageToSend); // Send the stored message} else if (this.isSpeaking) {this.pauseAudio();} else if (this.isAudioPaused) {3 unmodified lines}}getButtonIcon(): string {if (this.userInput.trim().length > 0) {return 'assets/images/chat/send-icon.png'; // Replace with your send icon image} else if (this.isSpeaking) {return 'assets/images/chat/pause-icon.png'; // Replace with your pause icon image} else if (this.isAudioPaused) {return 'assets/images/chat/resume-icon.png'; // Replace with your resume icon image} else {return 'assets/images/chat/microphone-icon.png'; // Replace with your microphone icon image}}addNewLine(event: KeyboardEvent): void {if (event.key === 'Enter' && event.shiftKey) {event.preventDefault(); // Prevent form submissionthis.userInput += '\n'; // Add a new line to the textarea}}adjustTextareaHeight(event: Event): void {const textarea = event.target as HTMLTextAreaElement;textarea.style.height = 'auto'; // Reset height to calculate new heighttextarea.style.height = `${textarea.scrollHeight}px`; // Adjust height based on content}handleEnterPress(event: KeyboardEvent): void {if (this.isSpeaking) {event.preventDefault(); // Prevent typing when AI is speakingreturn;}if (event.key === 'Enter' && !event.shiftKey) {event.preventDefault();this.handleButtonClick();} else if (event.key === 'Enter' && event.shiftKey) {event.preventDefault();this.userInput += '\n';}}getButtonIconClass(): string {return this.userInput.trim().length > 0? 'send-icon': this.isSpeaking? 'pause-icon': this.isAudioPaused? 'resume-icon' // Class for resume icon: 'microphone-icon';}11 unmodified lines}}}1234567891011123 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666 unmodified lines7374757677787980818283848586878889909192939495969798991001011021031041051061076 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421432 unmodified lines1461471481491501511521535 unmodified lines1591601611621631641651661671681691702 unmodified lines1731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372 unmodified lines2402412422432442452462472482492502512522532542552562572582592602612622632642652662672683 unmodified lines2722732742752762772782792802812822832842852862872882892902912922932942952961 unmodified line2982993003013023033043053063073083093103113123133143153163173183193203213223233243253262 unmodified lines3293303313323333341 unmodified line3363373383393403413423433443453463472 unmodified lines3503513523533543553563573583593603613623633643653663 unmodified lines37037137237337437537637737837938038138238338438538638738838939039139239339419 unmodified lines4144154164174184194202 unmodified lines4234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904913 unmodified lines49549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153211 unmodified lines544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578import { Component, Inject, OnDestroy, PLATFORM_ID, ChangeDetectorRef } from '@angular/core';import { ApiService } from './api.service';import { FormsModule } from '@angular/forms';import { CommonModule } from '@angular/common';import { Router, RouterModule } from '@angular/router';import { isPlatformBrowser } from '@angular/common';import { ViewChild, ElementRef } from '@angular/core';import { Renderer2 } from '@angular/core';import { Subscription } from 'rxjs';@Component({selector: 'app-chat',3 unmodified linesstyleUrl: './chat.component.css'})export class ChatComponent implements OnDestroy {showQuestions: boolean = false;userInput: string = '';messages: { from: string, text: string, timestamp: string; isPlaying?: boolean }[] = [];isTyping: boolean = false;@ViewChild('chatBox') chatBox!: ElementRef;isLoadingSpeech: boolean = false;selectedVoice: SpeechSynthesisVoice | null = null;errorMessage: string = "";recognition: any;speechSynthesisInstance: SpeechSynthesisUtterance | null = null;isListening: boolean = false;isProcessingSpeech: boolean = false;isSpeaking: boolean = false;isAudioPaused: boolean = false;isInputValid: boolean = false;suggestions: string[] = [];showMicPopup: boolean = false;isSubmitting: boolean = false;private responseSub?: Subscription;private lastFullAiText: string = '';ngAfterViewChecked() {setTimeout(() => {this.scrollToBottom();}, 100);}private scrollToBottom(): void {try {this.chatBox.nativeElement.scrollTop = this.chatBox.nativeElement.scrollHeight;} catch (err) { }}constructor(private apiService: ApiService,private cdr: ChangeDetectorRef,@Inject(PLATFORM_ID,) private platformId: object,private router: Router,private renderer: Renderer2) {window.speechSynthesis.onvoiceschanged = () => {console.log("Available Voices:", window.speechSynthesis.getVoices());};if (isPlatformBrowser(this.platformId)) {const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;if (SpeechRecognition) {6 unmodified linesif (event.results && event.results[0]) {const transcript = event.results[0][0].transcript.trim();console.log('Recognized speech:', transcript);this.userInput = transcript;this.sendMessage();this.recognition.stop();this.isListening = false;}};this.recognition.onerror = (event: any) => {console.error('Speech Recognition Error:', event.error);this.isProcessingSpeech = false;};} else {console.warn('Speech Recognition is not supported in this browser.');}window.addEventListener('beforeunload', this.handleUnload);}}private handleUnload = (): void => {if (window.speechSynthesis) {window.speechSynthesis.cancel();}};ngOnDestroy(): void {if (isPlatformBrowser(this.platformId)) {if (window.speechSynthesis) {window.speechSynthesis.cancel();}window.removeEventListener('beforeunload', this.handleUnload);}}6 unmodified linesthis.showMicPopup = false;}showHardcodedQuestions(): void {setTimeout(() => {this.showQuestions = true;}, 100);}hideHardcodedQuestions(): void {setTimeout(() => {this.showQuestions = false;}, 200);}selectHardcodedQuestion(question: string): void {this.userInput = question;this.showQuestions = false;setTimeout(() => {this.sendMessage();this.userInput = '';}, 100);}getSuggestions(): void {if (!this.userInput || this.userInput.trim().length < 1 || this.isSpeaking) {this.suggestions = [];return;}2 unmodified linesconsole.log("API Response:", response);if (response.suggestions) {this.suggestions = response.suggestions.filter((s: string) => s && s.trim().length > 0).map((s: string) => s.replace(/^\d+\.\s*/, ""));} else {this.suggestions = [];}5 unmodified lines);}selectSuggestion(suggestion: string): void {this.userInput = suggestion;this.suggestions = [];this.sendMessage();}sendMessage(inputText?: string): void {const message = inputText ? inputText.trim() : this.userInput.trim();if (!message) {2 unmodified lineslet sessionId = localStorage.getItem('session_id');this.messages.push({ from: 'user', text: message, timestamp: new Date().toLocaleTimeString() });this.userInput = '';this.isTyping = true;this.cdr.detectChanges();this.scrollToBottom();this.responseSub = this.apiService.askQuestion(message, sessionId).subscribe((response) => {this.isTyping = false;const explanation = (response?.response || 'No explanation available.').trim();if (response.session_id && !sessionId) {localStorage.setItem('session_id', response.session_id);}const lines: string[] = String(explanation).split('\n');const formatted: string = lines.map((line: string) => line.trim()).join('\n');this.messages.push({from: 'ai',text: formatted,timestamp: new Date().toLocaleTimeString(),});this.cdr.detectChanges();this.scrollToBottom();this.lastFullAiText = formatted;this.speakResponse(explanation);},(error) => {this.isTyping = false;const errorMessage = 'Error: Could not get a response from the server.';console.error('API Error:', error);this.messages.push({from: 'ai',text: errorMessage,timestamp: new Date().toLocaleTimeString(),});this.cdr.detectChanges();this.scrollToBottom();this.lastFullAiText = errorMessage;this.speakResponse(errorMessage);});}formatStructuredResponse(text: string): string {let formattedText = text.replace(/\n/g, '<br>').replace(/(\d+)\.\s/g, '<b>$1.</b> ').replace(/\•\s/g, '✔️ ').replace(/\-\s/g, '🔹 ').replace(/(\*\*)(.*?)\1/g, '<b>$2</b>');return formattedText;}speakResponse(responseText: string): void {if (!responseText) {console.warn('No response text provided for speech.');2 unmodified linesconsole.log('Initiating text-to-speech with response:', responseText);let lastAiMessage = this.messages.slice().reverse().find((msg) => msg.from === 'ai');if (!lastAiMessage) {lastAiMessage = { from: 'ai', text: '', timestamp: new Date().toLocaleTimeString() };this.messages.push(lastAiMessage);} else {lastAiMessage.text = '';}this.cdr.detectChanges();const words = responseText.split(' ');let currentWordIndex = 0;const speech = new SpeechSynthesisUtterance();speech.text = responseText;speech.lang = 'en-US';speech.pitch = 1;speech.rate = 1;this.isSpeaking = true;const voices = window.speechSynthesis.getVoices();let femaleVoice = voices.find(voice => voice.name === "Microsoft Zira - English (United States)");if (femaleVoice) {3 unmodified linesconsole.warn("Microsoft Zira not found, using default.");}speech.onboundary = (event) => {if (event.name === 'word' && currentWordIndex < words.length) {lastAiMessage!.text = words.slice(0, currentWordIndex + 1).join(' ');currentWordIndex++;this.cdr.detectChanges();}};speech.onend = () => {console.log('Speech ended.');this.isSpeaking = false;lastAiMessage!.text = responseText;this.cdr.detectChanges();};console.log('Starting speech synthesis...');window.speechSynthesis.speak(speech);}ngOnInit(): void {if (window.speechSynthesis.onvoiceschanged !== undefined) {window.speechSynthesis.onvoiceschanged = () => {1 unmodified line};}this.loadVoices();}loadVoices(): void {const voices = window.speechSynthesis.getVoices();if (!voices.length) {console.warn("No voices available yet, retrying...");setTimeout(() => this.loadVoices(), 500);return;}console.log("Available Voices:", voices.map(v => v.name));const preferredVoices = ["Google UK English Female","Google US English Female","Microsoft Zira - English (United States)","Microsoft Hazel - English (United Kingdom)","Google en-GB Female","Google en-US Female"];for (let voiceName of preferredVoices) {const foundVoice = voices.find(voice => voice.name === voiceName);if (foundVoice) {2 unmodified lines}}if (!this.selectedVoice) {this.selectedVoice = voices.find(voice => voice.name.toLowerCase().includes("female")) || voices[0];}1 unmodified lineconsole.log("Selected AI Voice:", this.selectedVoice?.name);}pauseAudio(): void {if (window.speechSynthesis.speaking && !window.speechSynthesis.paused) {window.speechSynthesis.pause();this.isAudioPaused = true;console.log('AI Speech Paused');this.cdr.detectChanges();}}2 unmodified lineswindow.speechSynthesis.resume();this.isAudioPaused = false;console.log('AI Speech Resumed');this.cdr.detectChanges();}}muteMicrophone(): void {console.log("Microphone muted");}startListening(): void {this.isListening = true;this.isProcessingSpeech = false;if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {navigator.mediaDevices3 unmodified linesconsole.log('Starting speech recognition...');this.recognition.start();this.recognition.onaudiostart = () => console.log('Audio capturing started.');this.recognition.onspeechstart = () => console.log('Speech has been detected.');this.recognition.onspeechend = () => console.log('Speech ended, processing...');this.recognition.onaudioend = () => console.log('Audio capturing ended.');this.recognition.onresult = (event: any) => {if (event.results && event.results[0]) {const transcript = event.results[0][0].transcript.trim();console.log('Recognized speech:', transcript);this.userInput = transcript;if (this.userInput.trim()) {console.log('Sending question automatically:', this.userInput);this.sendMessage();}this.recognition.stop();this.isListening = false;}};19 unmodified lines.catch((error) => {console.error('Microphone access denied:', error);this.errorMessage = 'Please enable microphone access to use this feature.';this.isListening = true;});} else {2 unmodified lines}stopListening(): void {this.isListening = false;if (this.recognition) {this.recognition.stop();}}toggleAudio(message: { text: string, isPlaying?: boolean }): void {if (this.speechSynthesisInstance && this.speechSynthesisInstance.text === message.text) {if (message.isPlaying) {window.speechSynthesis.pause();message.isPlaying = false;} else {window.speechSynthesis.resume();message.isPlaying = true;}} else {if (this.speechSynthesisInstance) {window.speechSynthesis.cancel();}this.messages.forEach((msg) => (msg.isPlaying = false));message.isPlaying = true;this.speechSynthesisInstance = new SpeechSynthesisUtterance(message.text);this.speechSynthesisInstance.lang = 'en-US';this.speechSynthesisInstance.pitch = 1;this.speechSynthesisInstance.rate = 1;this.speechSynthesisInstance.onend = () => {message.isPlaying = false;this.speechSynthesisInstance = null;};window.speechSynthesis.speak(this.speechSynthesisInstance);}}goToHome() {this.router.navigate(['/home']);}copySuccessIndex: number | null = null;copyToClipboard(text: string, index: number): void {navigator.clipboard.writeText(text).then(() => {this.copySuccessIndex = index;setTimeout(() => {this.copySuccessIndex = null;}, 2000);}).catch(err => {console.error('Failed to copy: ', err);});}checkInput() {this.isInputValid = this.userInput.trim().length > 0;}handleButtonClick(): void {if (this.userInput.trim().length > 0) {this.showQuestions = false;const messageToSend = this.userInput;this.userInput = '';this.sendMessage(messageToSend);} else if (this.isSpeaking) {this.pauseAudio();} else if (this.isAudioPaused) {3 unmodified lines}}getButtonIcon(): string {if (this.userInput.trim().length > 0) {return 'assets/images/chat/send-icon.png';} else if (this.isSpeaking) {return 'assets/images/chat/pause-icon.png';} else if (this.isAudioPaused) {return 'assets/images/chat/resume-icon.png';} else {return 'assets/images/chat/microphone-icon.png';}}addNewLine(event: KeyboardEvent): void {if (event.key === 'Enter' && event.shiftKey) {event.preventDefault();this.userInput += '\n';}}adjustTextareaHeight(event: Event): void {const textarea = event.target as HTMLTextAreaElement;textarea.style.height = 'auto';textarea.style.height = `${textarea.scrollHeight}px`;}getButtonIconClass(): string {return this.userInput.trim().length > 0? 'send-icon': this.isSpeaking? 'pause-icon': this.isAudioPaused? 'resume-icon': 'microphone-icon';}11 unmodified lines}}stopSpeaking(): void {try {if (window.speechSynthesis.speaking || window.speechSynthesis.paused) {window.speechSynthesis.cancel();}} catch { }(this as any).speechSynthesisInstance = null;if (this.responseSub && !this.responseSub.closed) {this.responseSub.unsubscribe();}this.isSpeaking = false;this.isAudioPaused = false;this.isTyping = false;}handleEnterPress(event: KeyboardEvent): void {if (this.isSpeaking) {event.preventDefault();return;}if (event.key === 'Enter' && !event.shiftKey) {event.preventDefault();const text = (this.userInput || '').trim();if (text) this.sendMessage();}}}
src/app/chat/chat.component.css+96-182
src/app/chat/chat.component.html+18-47
src/app/chat/chat.component.ts+133-222
src/assets/images/chat/control.pngAdded

Large File Pointer Details
- SHA256: 2d37166a1708f4d6e27babc1b9bc408c505e5b79e27a7a81ef0ef29f1680ac65
- Pointer size: 129 Bytes
- Size of remote file: 5.89 kB
src/assets/images/chat/stop-button.pngAdded

Large File Pointer Details
- SHA256: a01d5cf4aa76de7da282c98decad20b19a4fe37076ec9f195e850966cdae8389
- Pointer size: 129 Bytes
- Size of remote file: 4.08 kB
src/assets/images/chat/stop.pngAdded

Large File Pointer Details
- SHA256: 5c10275efe01a0421881c8a70652110158155578243833c1434472f6cbad805f
- Pointer size: 130 Bytes
- Size of remote file: 31.7 kB