0% found this document useful (0 votes)
5 views13 pages

Program

Uploaded by

lavanyar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views13 pages

Program

Uploaded by

lavanyar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

<!

DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Health Assistant</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #C71585;
}

/* Front Page Styles */


#front-page {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background: linear-gradient(to bottom right, #3951ff, #fa3c7b);
color: white;
text-align: center;
}

#front-page h1 {
font-size: 3rem;
margin: 0;
font-weight: bold;
}

#front-page p {
font-size: 1.5rem;
margin: 20px 0;
max-width: 600px;
}

#front-page button {
background-color: white;
color: #3951ff;
border: none;
padding: 15px 30px;
font-size: 1.2rem;
font-weight: bold;
border-radius: 8px;
cursor: pointer;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}

#front-page button:hover {
transform: translateY(-3px);
box-shadow: 0 6px 10px rgba(0, 0, 0, 0.15);
}

#front-page button:active {
transform: translateY(1px);
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

/* Health Assistant Section Styles */


#health-assistant {
display: none;
padding: 20px;
}

header {
background-color: #3951ff;
color: white;
padding: 20px;
text-align: center;
}

h1 {
margin: 0;
font-size: 2.5rem;
}

section {
margin: 20px;
padding: 20px;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

label {
font-weight: bold;
display: block;
margin-bottom: 10px;
}

textarea, input {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
}

button {
background-color: #28a745;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
}

button:hover {
background-color: #218838;
}

.notification {
margin-top: 10px;
padding: 10px;
border-radius: 4px;
}

.notification.success {
background-color: #e6ffe6;
color: #28a745;
}

.notification.error {
background-color: #ffe6e6;
color: #dc3545;
}

footer {
text-align: center;
padding: 10px;
background-color: #333;
color: white;
}
</style>
</head>
<body>

<!-- Front Page -->


<div class="front-page" id="front-page">
<h1>Welcome to HealthAura</h1>
<p>Your AI-Powered Health Assistant</p>
<button id="start-button">Get Started</button>
</div>

<!-- Main App -->


<div class="hidden" id="main-app">
<header>
<h1>HealthAura</h1>
<p>Enter your medical history and symptoms to get personalized guidance
powered by AI.</p>
</header>

<section id="medical-history">
<h2>Your Medical History</h2>
<div id="inputError" style="'display:none'">
</div>
<form id="history-form">

<label for="myfile">Upload your previour reports if any :</label>


<input type="file" id="myfile" name="myfile">

<label for="chronic-conditions"> <font color="red"> * </font>Do you


have any chronic conditions? (e.g., asthma, diabetes)</label>
<textarea id="chronic-conditions"
name="chronic-conditions"></textarea>

<label for="current-medication">Current medications you


take:</label>
<textarea id="current-medication"
name="current-medication"></textarea>

<label for="allergies">Any known allergies?</label>


<textarea id="allergies" name="allergies"></textarea>

<label for="lifestyle">Lifestyle habits (e.g., smoking,


exercise):</label>
<textarea id="lifestyle" name="lifestyle"></textarea>

<button type="button" onclick="saveMedicalHistory()"> Save Medical


History</button>
<button type="button" onclick="generateText('asthma')">
generateTexty</button>

</form>
</section>

<section id="current-symptoms">
<h2>Report Current Symptoms</h2>
<form id="symptom-form">
<label for="symptoms">Describe your current symptoms:</label>
<textarea id="symptoms" name="symptoms" required placeholder="e.g.,
severe headache, fever, breathing issues"></textarea>

<label for="symptom-duration">How long have you had these


symptoms?</label>
<input type="text" id="symptom-duration" name="symptom-duration"
required placeholder="e.g., 2 days, 1 week">

<label for="symptom-trigger">Is there anything that triggers or


worsens the symptoms?</label>
<textarea id="symptom-trigger" name="symptom-trigger"
placeholder="e.g., exercise, certain foods, stress"></textarea>

<button type="button" onclick="getEnhancedRecommendation()">Get AI


Recommendation</button>
</form>
</section>

<div id="loading" class="loading">Analyzing symptoms and generating


recommendation</div>

<section id="recommendation">
<h2>AI Recommended Action</h2>
<div id="ai-recommendation">
Once you submit your symptoms, the AI will provide a personalized
recommendation based on your medical history and current symptoms.
</div>
</section>

</div>

<script>
// Debugging Logs
alert(1)
console.log('Script Loaded.');

document.addEventListener('DOMContentLoaded', () => {
console.log('DOM Content Loaded.');

const frontPage = document.getElementById('front-page');


const mainApp = document.getElementById('main-app');
const startButton = document.getElementById('start-button');

// Prevent double-click or multiple event registrations


startButton.removeEventListener('click', transitionToApp); // Clear any
existing listeners

startButton.addEventListener('click', transitionToApp);
function transitionToApp() {
console.log('Button clicked. Transitioning...');

frontPage.classList.add('hidden'); // Hide the front page


mainApp.classList.remove('hidden'); // Show the main app

}
});

function saveMedicalHistory(){
try {
inputError.innerHTML='';
const medicalHistory = {
chronicConditions:
document.getElementById('chronic-conditions').value.trim(),
currentMedication:
document.getElementById('current-medication').value.trim(),
allergies: document.getElementById('allergies').value.trim(),
lifestyle: document.getElementById('lifestyle').value.trim()
};

if (!medicalHistory.chronicConditions &&
!medicalHistory.currentMedication &&
!medicalHistory.allergies && !medicalHistory.lifestyle &&
!myfile.value) {
inputError.innerHTML = `<div class="mild"><p>Please fill in at
least one field of your medical history.</p></div>`;
return;
}

localStorage.setItem('medicalHistory', JSON.stringify(medicalHistory));

const aiRecommendation = document.getElementById('ai-recommendation');

inputError.innerHTML = `<div class="mild"><p>Medical history saved


successfully! You can now report your current symptoms.</p></div>`;
aiRecommendation.innerHTML = `<div class="mild"><p>Medical history
saved successfully! You can now report your current symptoms.</p></div>`;

} catch (error) {
const aiRecommendation = document.getElementById('ai-recommendation');
inputError.innerHTML = `<div class="error"> <p>Error saving medical
history:error.message</p></div>`;
}

}
// Function to generate text using a generative AI API

async function generateText(prompt) {

const apiKey = 'AIzaSyBPlqtI5pEUX2PGv_dmcKYswbfL3pLqDnE'; // Replace with your


API key
//const apiUrl =
'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-lates
t:generateContent'; // Replace with the actual API URL
const apiUrl =
'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-lates
t:generateContent';

const response = await fetch(apiUrl, {


method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
prompt: prompt,
max_tokens: 150 // Specify the number of tokens (words) you want in the
response
})
});
//alert(prompt+'Prompt 123'); // Bavishya comment
const aiRecommendation = document.getElementById('ai-recommendation');
aiRecommendation.innerHTML = prompt;
const data = await response.json();
const dataString = JSON.stringify(data, null, 2);
//alert(dataString) // Bavishya comment
aiRecommendation.innerHTML = dataString
return data.generated_text; // Adjust based on the actual response format
}

/* NOT REQUIRED
let generatedText; // Declare the variable outside

generateText(prompt)
.then(text => {
generatedText = text; // Assign the value
alert(generatedText);
console.log('Generated Text:', generatedText);
})
.catch(error => {
console.error('Error:', error);
}); */
// Replace with your actual API key
const apiKey = 'AIzaSyALrygyXCKsita6HGSDVCSDsqfDhQP-2gs';

// Define the API URL for the generative model


const apiUrl =
'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-lates
t:generateContent';

// Data for the request (the prompt you want the model to respond to)
const requestData = {
prompt: "Write a short story about a brave knight who saves a kingdom.",
maxOutputTokens: 100, // Maximum number of tokens (words) in the output
(optional)
temperature: 0.7, // Controls creativity: 0.0 (conservative) to 1.0
(creative)
topP: 0.9 // Controls diversity of responses (optional)
};

// Function to send the request


async function generateContent() {
alert(2222);
try {
const response = await fetch(`${apiUrl}?key=${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Ensure the request body
is JSON
},
body: JSON.stringify(requestData) // Convert requestData to JSON
format
});

// Check if the response was successful


if (!response.ok) {
throw new Error('Network response was not ok: ' +
response.statusText);
}

// Parse the JSON response


const data = await response.json();

// Extract and display the generated text


console.log('Generated Content:', data.generatedContent);
alert('Generated Content: ' + data.generatedContent); // Show it in an
alert box
} catch (error) {
alert('Error during API call:', error);
}
}

// Call the function to generate content


async function getEnhancedRecommendation() {
const symptomsInput = document.getElementById('symptoms');
const durationInput = document.getElementById('symptom-duration');
const loadingDiv = document.getElementById('loading');
const aiRecommendation = document.getElementById('ai-recommendation');

if (!symptomsInput.value.trim() || !durationInput.value.trim()) {
aiRecommendation.innerHTML = `<div class="error"><p>Please describe your
symptoms and specify their duration.</p></div>`;
return;
}

loadingDiv.style.display = 'block';
const healthAI = new EnhancedHealthAssistantAI();

try {

const medicalHistory = JSON.parse(localStorage.getItem('medicalHistory')) || {


chronicConditions: '',
currentMedication: '',
allergies: '',
lifestyle: ''
};

const currentSymptoms = {
symptoms: symptomsInput.value.trim(),
duration: durationInput.value.trim(),
triggers: document.getElementById('symptom-trigger').value.trim()
};

healthAI.setMedicalHistory(medicalHistory);
healthAI.setCurrentSymptoms(currentSymptoms);

const recommendation = await healthAI.generateEnhancedRecommendation();

aiRecommendation.className = RISK_LEVELS[recommendation.riskLevel].class;
//aiRecommendation.innerHTML='"Drink plenty of water.", "Eat a balanced diet.",
"Exercise regularly.", "Get enough sleep.", "Wash your hands frequently";'
//aiRecommendation.innerHTML = `<div><h3>Risk Level:
${recommendation.riskLevel.to UpperCase()}</h3><p><strong>Recommended
Action:</strong><br>${recommendation.primaryAction}</p>${recommendation.specifi
cRecommendations.length > 0 ? `<p><strong>Specific
Recommendations:</strong></p><ul>${recommendation.specificRecommendations.map(r
ec => <li>${rec}</li>).join('')}</ul>` : ''}<p><em>AI Confidence Level:
${Math.round(recommendation.aiAnalysis.confidence)}%</em></p></div><p
class="disclaimer"><strong>Disclaimer:</strong><br>${recommendation.disclaimer}
</p></div>`;
} catch (error) {
console.error("Error generating AI recommendation:", error);
aiRecommendation.innerHTML = `<div class="error"> <p>There was an error
generating the recommendation. Please try again later.</p><p>Error details:
${error.message}</p></div>`;
} finally {
loadingDiv.style.display = 'none';
}
}

</script>
<script>

function saveMedicalHistory2() {
try {
const medicalHistory = {
chronicConditions:
document.getElementById('chronic-conditions').value.trim(),
currentMedication:
document.getElementById('current-medication').value.trim(),
allergies: document.getElementById('allergies').value.trim(),
lifestyle: document.getElementById('lifestyle').value.trim()
};

if (!medicalHistory.chronicConditions &&
!medicalHistory.currentMedication &&
!medicalHistory.allergies && !medicalHistory.lifestyle) {
throw new Error("Please fill in at least one field of your medical
history.");
}

localStorage.setItem('medicalHistory', JSON.stringify(medicalHistory));

const aiRecommendation = document.getElementById('ai-recommendation');


aiRecommendation.innerHTML = `<div class="mild"><p>Medical history saved
successfully! You can now report your current symptoms.</p></div>`;
} catch (error) {
const aiRecommendation = document.getElementById('ai-recommendation');
aiRecommendation.innerHTML = `<div class="error"> <p>Error saving
medical history:error.message</p></div>`;
}
}

async function getEnhancedRecommendation1() {


const symptomsInput = document.getElementById('symptoms');
const durationInput = document.getElementById('symptom-duration');
const loadingDiv = document.getElementById('loading');
const aiRecommendation = document.getElementById('ai-recommendation');

alert(123)
if (!symptomsInput.value.trim() || !durationInput.value.trim()) {
aiRecommendation.innerHTML = `
<div class="error">
<p>Please describe your symptoms and specify their duration.</p>
</div>
`;
return;
}

loadingDiv.style.display = 'block';
const healthAI = new EnhancedHealthAssistantAI();

try {

const medicalHistory =
JSON.parse(localStorage.getItem('medicalHistory')) || {
chronicConditions: '',
currentMedication: '',
allergies: '',
lifestyle: ''
};

const currentSymptoms = {
symptoms: symptomsInput.value.trim(),
duration: durationInput.value.trim(),
triggers: document.getElementById('symptom-trigger').value.trim()
};

healthAI.setMedicalHistory(medicalHistory);
healthAI.setCurrentSymptoms(currentSymptoms);

const recommendation = await healthAI.generateEnhancedRecommendation();

aiRecommendation.className =
RISK_LEVELS[recommendation.riskLevel].class;
aiRecommendation.innerHTML = `
<div>
<h3>Risk Level: ${recommendation.riskLevel.to UpperCase()}</h3>
<p><strong>Recommended Action:</strong><br>
${recommendation.primaryAction}</p>

${recommendation.specificRecommendations.length > 0 ? `
<p><strong>Specific Recommendations:</strong></p>
<ul>${recommendation.specificRecommendations.map(rec =>
`<li>${rec}</li>`).join('')}</ul>
` : ''}

<div class="meta-analysis">
<p><strong>AI Analysis Insights:</strong></p>
<ul>

${recommendation.aiAnalysis.additionalInsights.map(insight =>
`<li>${insight}</li>`
).join('')}
</ul>

${recommendation.aiAnalysis.suggestedTests.length > 0 ? `
<p><strong>Suggested Medical Tests to Discuss with Your
Doctor:</strong></p>
<ul>
${recommendation.aiAnalysis.suggestedTests.map(test
=>
`<li>${test}</li>`
).join('')}
</ul>
` : ''}

<p><em>AI Confidence Level:


${Math.round(recommendation.aiAnalysis.confidence)}%</em></p>
</div>

<p class="disclaimer"><strong>Disclaimer:</strong><br>
${recommendation.disclaimer}</p>
</div>
`;
} catch (error) {
console.error("Error generating AI recommendation:", error);
aiRecommendation.innerHTML = `
<div class="error">
<p>There was an error generating the recommendation. Please try
again later.</p>
<p>Error details: ${error.message}</p>
</div>
`;
} finally {
loadingDiv.style.display = 'none';
}
}

document.getElementById('history-form').addEventListener('keypress',
function(e) {
if (e.key === 'Enter') {
e.preventDefault();
saveMedicalHistory();
}
});

document.getElementById('symptom-form').addEventListener('keypress',
function(e) {
if (e.key === 'Enter') {
e.preventDefault();
getEnhancedRecommendation();
}
});

window.addEventListener('load', function() {
try {
const savedHistory = JSON.parse(localStorage.getItem('medicalHistory'));
if (savedHistory) {
document.getElementById('chronic-conditions').value =
savedHistory.chronicConditions || '';
document.getElementById('current-medication').value =
savedHistory.currentMedication || '';
document.getElementById('allergies').value = savedHistory.allergies
|| '';
document.getElementById('lifestyle').value = savedHistory.lifestyle
|| '';
}
} catch (error) {
console.error("Error loading saved medical history:", error);
}
});

</script>
</body>
</html>

You might also like