Upload 2 files
Browse filesFiles changed (2)
- auth.htmlAdded+1510
- file_pipeline.pyAdded+397
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510<!DOCTYPE html><html lang="en" data-bs-theme="dark"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GAKR AI - Login/Signup</title> <link rel="stylesheet" href="https://cdn.replit.com/agent/bootstrap-agent-dark-theme.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> <style> :root { --gakr-blue: #4285F4; --gakr-blue-dark: #1a73e8; --gakr-blue-light: #e8f0fe; --gakr-grey-text: #5f6368; --gakr-grey-hover-bg: rgba(95, 99, 104, 0.1); }
:root[data-bs-theme="dark"] { --gakr-blue: #8ab4f8; --gakr-blue-dark: #669df6; --gakr-blue-light: rgba(138, 180, 248, 0.1); --gakr-grey-text: #bdc1c6; --gakr-grey-hover-bg: rgba(189, 193, 198, 0.1); }
@import url('https://fonts.googleapis.com/css?family=Poppins:400,500,600,700&display=swap');
* { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
html, body { display: flex; flex-direction: column; align-items: center; height: 100%; width: 100%; background: -webkit-linear-gradient(left, #003366,#004080,#0059b3 , #0073e6); color: var(--bs-body-color); padding-top: 5vh; padding-bottom: 5vh; min-height: 100vh; /* Allow space for modal overlay */ position: relative; }
::selection { background: var(--gakr-blue); color: #fff; }
.wrapper { overflow: hidden; max-width: 440px; width: 90%; background: var(--bs-body-bg); box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.5); padding: 30px; border-radius: 15px; margin-top: 10px; margin-bottom: 10px; z-index: 10; /* Ensure wrapper is below modal but above background */ }
.wrapper .title-text { display: flex; width: 200%; }
.wrapper .title { width: 50%; font-size: 35px; font-weight: 600; text-align: center; transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55); color: var(--bs-body-color); }
.wrapper .slide-controls { position: relative; display: flex; height: 50px; width: 100%; overflow: hidden; margin: 30px 0 10px 0; justify-content: space-between; border: 1px solid var(--bs-border-color); border-radius: 15px; }
.slide-controls .slide { height: 100%; width: 100%; color: var(--bs-body-color); font-size: 18px; font-weight: 500; text-align: center; line-height: 48px; cursor: pointer; z-index: 1; transition: all 0.6s ease; }
.slide-controls label.signup{ color: var(--bs-body-color); }
.slide-controls .slider-tab { position: absolute; height: 100%; width: 50%; left: 0; z-index: 0; border-radius: 15px; background: var(--gakr-blue); transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55); }
input[type="radio"]{ display: none; }
#signup:checked ~ .slider-tab{ left: 50%; } #signup:checked ~ label.signup{ color: #fff; cursor: default; user-select: none; } #signup:checked ~ label.login{ color: var(--bs-body-color); } #login:checked ~ label.signup{ color: var(--bs-body-color); } #login:checked ~ label.login{ color: #fff; cursor: default; user-select: none; }
.wrapper .form-container { width: 100%; overflow: hidden; }
.form-container .form-inner { display: flex; width: 200%; }
.form-container .form-inner form { width: 50%; transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55); }
.form-inner form .field { height: 50px; width: 100%; margin-top: 20px; position: relative; }
.form-inner form .field:has(+ .field.btn) { margin-bottom: 25px; }
.form-inner form .field input{ height: 100%; width: 100%; outline: none; padding-left: 15px; border-radius: 15px; border: 1px solid var(--bs-border-color); border-bottom-width: 2px; font-size: 17px; transition: all 0.3s ease; color: var(--bs-body-color); background-color: var(--bs-body-bg); }
.form-inner form .field input.error { border-color: red; }
.form-inner form .field input::placeholder{ color: var(--bs-secondary-color); transition: all 0.3s ease; }
form .field input:focus::placeholder{ color: var(--gakr-blue); }
.form-inner form .pass-link{ margin-top: 5px; font-size: 0.9rem; text-align: right; /* Align to right */ }
.form-inner form .signup-link{ text-align: center; margin-top: 30px; font-size: 0.9rem; }
.form-inner form .pass-link a, .form-inner form .signup-link a{ color: var(--gakr-blue); text-decoration: none; transition: color 0.2s ease-in-out; }
.form-inner form .pass-link a:hover, form-inner form .signup-link a:hover{ text-decoration: underline; color: var(--gakr-blue-dark); }
form .btn { height: 50px; width: 100%; margin-top: 20px; border-radius: 15px; position: relative; overflow: hidden; background: none; transition: none; }
form .btn input[type="submit"] { height: 100%; width: 100%; z-index: 1; position: relative; background: var(--gakr-blue); border: none; color: #fff; padding: 0; border-radius: 15px; font-size: 20px; font-weight: 500; cursor: pointer; transition: background-color 0.2s ease-in-out, transform 0.1s ease-in-out; display: flex; align-items: center; justify-content: center; }
form .btn input[type="submit"]:hover { background-color: var(--gakr-blue-dark); }
form .btn input[type="submit"]:active { transform: scale(0.98); transition: background-color 0s, transform 0.1s; }
.error-message { color: red; font-size: 0.8rem; margin-top: 4px; position: absolute; bottom: -18px; left: 15px; white-space: nowrap; }
.form-message { text-align: center; margin-top: 20px; font-size: 0.9rem; min-height: 1.2em; }
.form-message.success { color: green; }
.form-message.error { color: red; }
.loading-spinner { display: inline-block; width: 18px; height: 18px; border: 3px solid rgba(255, 255, 255, .3); border-radius: 50%; border-top-color: #fff; animation: spin 1s ease-in-out infinite; margin-left: 10px; vertical-align: middle; }
@keyframes spin { to { -webkit-transform: rotate(360deg); } }
.form-inner form .btn input[type="submit"]:disabled { opacity: 0.7; cursor: not-allowed; position: relative; }
/* --- Modal Styles --- */ .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.6); /* Semi-transparent black overlay */ display: flex; justify-content: center; align-items: center; z-index: 100; /* On top of everything */ visibility: hidden; /* Hidden by default */ opacity: 0; transition: visibility 0s, opacity 0.3s ease-in-out; }
.modal-overlay.show { visibility: visible; opacity: 1; }
.modal-content { background-color: var(--bs-body-bg); padding: 30px; border-radius: 15px; box-shadow: 0px 5px 20px rgba(0, 0, 0, 0.7); text-align: center; max-width: 350px; width: 80%; transform: translateY(-20px); /* Slight animation on show */ transition: transform 0.3s ease-in-out; }
.modal-overlay.show .modal-content { transform: translateY(0); }
.modal-message { font-size: 1.1rem; margin-bottom: 25px; color: var(--bs-body-color); } .modal-message p { margin-bottom: 10px; /* Spacing for paragraphs in modal message */ line-height: 1.4; } .modal-message strong { font-size: 1.2rem; /* Heading for attempts message */ display: block; margin-bottom: 15px; } .modal-message ul { list-style: none; padding: 0; margin-bottom: 20px; } .modal-message ul li { margin-bottom: 8px; font-size: 1rem; }
.modal-button { background-color: var(--gakr-blue); color: #fff; border: none; padding: 10px 25px; border-radius: 10px; font-size: 1rem; cursor: pointer; transition: background-color 0.2s ease-in-out, transform 0.1s ease-in-out; }
.modal-button:hover { background-color: var(--gakr-blue-dark); }
.modal-button:active { transform: scale(0.98); } .modal-buttons-stacked { display: flex; flex-direction: column; /* Stack buttons vertically */ gap: 10px; margin-top: 20px; }
.modal-buttons-stacked .modal-button { width: 100%; /* Make buttons full width */ }
.modal-buttons-inline { display: flex; justify-content: space-between; /* Space them out */ gap: 15px; margin-top: 20px; } .modal-buttons-inline .modal-button { flex-grow: 1; /* Allow buttons to grow to fill space */ max-width: none; /* Override max-width from .modal-buttons */ }
/* Eye icon styles */ .field .toggle-password { position: absolute; right: 15px; top: 50%; transform: translateY(-50%); cursor: pointer; color: var(--bs-secondary-color); font-size: 0.9rem; }
.field .toggle-password:hover { color: var(--gakr-blue); }
/* Added styles for Forgot/Reset Modals */ .modal-form { text-align: left; margin-top: 20px; } .modal-form .field { margin-bottom: 15px; height: auto; /* Override default field height */ } .modal-form label { display: block; margin-bottom: 5px; font-size: 0.9rem; color: var(--bs-body-color); } .modal-form input[type="text"], .modal-form input[type="email"], .modal-form input[type="password"] { width: 100%; padding: 10px 15px; border: 1px solid var(--bs-border-color); border-radius: 10px; background-color: var(--bs-body-bg); color: var(--bs-body-color); box-sizing: border-box; /* Crucial for consistent width */ } .modal-form .error-message { position: static; /* Remove absolute positioning */ margin-top: 5px; margin-left: 0; white-space: normal; /* Allow message to wrap */ } .modal-buttons { display: flex; justify-content: center; gap: 15px; margin-top: 20px; } .modal-buttons button { width: 100%; max-width: 150px; } </style></head><body>
<div class="wrapper"> <div class="title-text"> <div class="title login">Login Form</div> <div class="title signup">Signup Form</div> </div> <div class="form-container"> <div class="slide-controls"> <input type="radio" name="slide" id="login" checked> <input type="radio" name="slide" id="signup"> <label for="login" class="slide login">Login</label> <label for="signup" class="slide signup">Signup</label> <div class="slider-tab"></div> </div> <div class="form-inner"> <form action="#" class="login" id="loginForm"> <div class="field"> <input type="text" placeholder="Username or Email" required id="loginUsernameOrEmail" name="username_or_email"> <div class="error-message" id="loginUsernameOrEmailError"></div> </div> <div class="field"> <input type="password" placeholder="Password" required id="loginPassword" name="password"> <span class="toggle-password fa-solid fa-eye-slash"></span> <div class="error-message" id="loginPasswordError"></div> </div> <div class="pass-link"><a href="#" id="forgotPasswordLink">Forgot password?</a></div> <div class="field btn"> <input type="submit" value="Login"> </div> <div class="signup-link">Not a member? <a href="">Signup now</a></div> </form> <form action="#" class="signup" id="signupForm"> <div class="field"> <input type="text" placeholder="Name" required id="signupName" name="name"> <div class="error-message" id="signupNameError"></div> </div> <div class="field"> <input type="text" placeholder="Email Address" required id="signupEmail" name="email"> <div class="error-message" id="signupEmailError"></div> </div> <div class="field"> <input type="password" placeholder="Password" required id="signupPassword" name="password"> <span class="toggle-password fa-solid fa-eye-slash"></span> <div class="error-message" id="signupPasswordError"></div> </div> <div class="field"> <input type="password" placeholder="Confirm password" required id="signupConfirmPassword" name="confirm_password"> <span class="toggle-password fa-solid fa-eye-slash"></span> <div class="error-message" id="signupConfirmPasswordError"></div> </div> <div class="field btn"> <input type="submit" value="Signup"> </div> </form> </div> </div> <div class="form-message" id="generalFormMessage"></div> </div>
<div class="modal-overlay" id="customModal"> <div class="modal-content"> <div class="modal-message" id="modalMessage"></div> <div id="modalButtonsContainer" class="modal-buttons"> </div> </div> </div>
<div class="modal-overlay" id="forgotPasswordRequestModal"> <div class="modal-content"> <p class="modal-message" id="forgotModalMessage">Enter your registered email to request a password reset.</p> <form id="forgotPasswordRequestForm" class="modal-form"> <div class="field"> <label for="forgotEmail">Email:</label> <input type="email" id="forgotEmail" name="email" required> <div class="error-message" id="forgotEmailError"></div> </div> <div class="modal-buttons-stacked"> <button type="submit" class="modal-button" id="forgotSubmitButton">Request OTP</button> <button type="button" class="modal-button" id="forgotCancelButton" style="background-color: var(--bs-secondary-color);">Cancel</button> </div> </form>
<div id="otpSection" style="display: none;"> <form id="verifyOtpForm" class="modal-form"> <div class="field"> <label for="otpInput">Enter OTP:</label> <input type="text" id="otpInput" name="otp" required maxlength="6" pattern="\d{6}" title="Please enter a 6-digit OTP"> <div class="error-message" id="otpError"></div> </div> <div class="modal-buttons-stacked"> <button type="submit" class="modal-button" id="verifyOtpButton">Verify OTP</button> <button type="button" class="modal-button" id="resendOtpButton" style="background-color: var(--bs-secondary-color);">Send Again</button> <button type="button" class="modal-button" id="otpCancelButton" style="background-color: var(--bs-secondary-color);">Cancel</button> </div> </form> </div> </div> </div>
<div class="modal-overlay" id="resetPasswordModal"> <div class="modal-content"> <p class="modal-message">Enter your new password.</p> <form id="resetPasswordForm" class="modal-form"> <div class="field"> <label for="resetEmail">Email:</label> <input type="email" id="resetEmail" name="email" required readonly style="background-color: var(--bs-secondary-bg); cursor: not-allowed;"> <div class="error-message" id="resetEmailError"></div> </div> <div class="field"> <label for="newPassword">New Password:</label> <input type="password" id="newPassword" name="new_password" required> <span class="toggle-password fa-solid fa-eye-slash"></span> <div class="error-message" id="newPasswordError"></div> </div> <div class="field"> <label for="confirmNewPassword">Confirm New Password:</label> <input type="password" id="confirmNewPassword" name="confirm_new_password" required> <span class="toggle-password fa-solid fa-eye-slash"></span> <div class="error-message" id="confirmNewPasswordError"></div> </div> <div class="modal-buttons-stacked"> <button type="submit" class="modal-button" id="resetSubmitButton">Reset Password</button> <button type="button" class="modal-button" id="resetCancelButton" style="background-color: var(--bs-secondary-color);">Cancel</button> </div> </form> </div> </div>
<script> document.addEventListener('DOMContentLoaded', function() { const loginText = document.querySelector(".title-text .login"); const loginFormDiv = document.querySelector("form.login"); const signupLink = document.querySelector("form .signup-link a"); const loginRadio = document.getElementById('login'); const signupRadio = document.getElementById('signup');
const loginForm = document.getElementById('loginForm'); const signupForm = document.getElementById('signupForm');
// Existing form inputs and error displays const loginUsernameOrEmailInput = document.getElementById('loginUsernameOrEmail'); const loginPasswordInput = document.getElementById('loginPassword'); const loginSubmitButton = loginForm ? loginForm.querySelector('input[type="submit"]') : null;
const signupNameInput = document.getElementById('signupName'); const signupEmailInput = document.getElementById('signupEmail'); const signupPasswordInput = document.getElementById('signupPassword'); const signupConfirmPasswordInput = document.getElementById('signupConfirmPassword'); const signupSubmitButton = signupForm ? signupForm.querySelector('input[type="submit"]') : null;
const loginUsernameOrEmailError = document.getElementById('loginUsernameOrEmailError'); const loginPasswordError = document.getElementById('loginPasswordError');
const signupNameError = document.getElementById('signupNameError'); const signupEmailError = document.getElementById('signupEmailError'); const signupPasswordError = document.getElementById('signupPasswordError'); const signupConfirmPasswordError = document.getElementById('signupConfirmPasswordError');
const generalFormMessage = document.getElementById('generalFormMessage');
// Modal elements (main alert modal) const customModal = document.getElementById('customModal'); const modalMessageDiv = document.getElementById('modalMessage'); const modalButtonsContainer = document.getElementById('modalButtonsContainer');
// Forgot Password Request & OTP Modals elements const forgotPasswordLink = document.getElementById('forgotPasswordLink'); const forgotPasswordRequestModal = document.getElementById('forgotPasswordRequestModal'); // The main overlay for forgot/otp const forgotModalMessage = document.getElementById('forgotModalMessage'); // Message within the forgot/otp modal
// Elements for Step 1: Request Email const forgotPasswordRequestForm = document.getElementById('forgotPasswordRequestForm'); const forgotEmailInput = document.getElementById('forgotEmail'); const forgotEmailError = document.getElementById('forgotEmailError'); const forgotSubmitButton = document.getElementById('forgotSubmitButton'); const forgotCancelButton = document.getElementById('forgotCancelButton');
// Elements for Step 2: Enter OTP const otpSection = document.getElementById('otpSection'); // The container for OTP input and buttons const verifyOtpForm = document.getElementById('verifyOtpForm'); const otpInput = document.getElementById('otpInput'); const otpError = document.getElementById('otpError'); const verifyOtpButton = document.getElementById('verifyOtpButton'); const resendOtpButton = document.getElementById('resendOtpButton'); const otpCancelButton = document.getElementById('otpCancelButton');
// Reset Password Modal elements (Step 3: New Password) const resetPasswordModal = document.getElementById('resetPasswordModal'); const resetPasswordForm = document.getElementById('resetPasswordForm'); const resetEmailInput = document.getElementById('resetEmail'); // Hidden but read-only email field const newPasswordInput = document.getElementById('newPassword'); const confirmNewPasswordInput = document.getElementById('confirmNewPassword'); const resetEmailError = document.getElementById('resetEmailError'); // Error for reset email (should be rare) const newPasswordError = document.getElementById('newPasswordError'); const confirmNewPasswordError = document.getElementById('confirmNewPasswordError'); const resetSubmitButton = document.getElementById('resetSubmitButton'); const resetCancelButton = document.getElementById('resetCancelButton');
// New: Login Attempt Counter let loginAttempts = 0; const MAX_LOGIN_ATTEMPTS = 3;
// Stores the email across the forgot password/OTP/reset flow let currentForgotEmail = '';
// Function to clear all error messages and input error classes function clearErrors(formType = 'all') { if (formType === 'all' || formType === 'main') { document.querySelectorAll('.error-message').forEach(el => el.textContent = ''); document.querySelectorAll('.form-inner form .field input').forEach(el => el.classList.remove('error')); if (generalFormMessage) { generalFormMessage.textContent = ''; generalFormMessage.className = 'form-message'; } } if (formType === 'all' || formType === 'forgot') { if (forgotEmailError) forgotEmailError.textContent = ''; if (forgotEmailInput) forgotEmailInput.classList.remove('error'); // Also clear the general forgotModalMessage when resetting for new flow if (forgotModalMessage) forgotModalMessage.innerHTML = 'Enter your registered email to request a password reset.'; } if (formType === 'all' || formType === 'otp') { if (otpError) otpError.textContent = ''; if (otpInput) otpInput.classList.remove('error'); } if (formType === 'all' || formType === 'reset') { if (resetEmailError) resetEmailError.textContent = ''; if (newPasswordError) newPasswordError.textContent = ''; if (confirmNewPasswordError) confirmNewPasswordError.textContent = ''; if (resetEmailInput) resetEmailInput.classList.remove('error'); if (newPasswordInput) newPasswordInput.classList.remove('error'); if (confirmNewPasswordInput) confirmNewPasswordInput.classList.remove('error'); } }
// Function to display general form-level message (below the forms) function displayFormMessage(message, type = 'info') { if (generalFormMessage) { generalFormMessage.textContent = message; generalFormMessage.className = 'form-message ' + type; } }
// Universal modal display function function showCustomModal(modalElement) { modalElement.classList.add('show'); }
// Universal modal hide function function hideCustomModal(modalElement) { modalElement.classList.remove('show'); clearErrors(); // Clear all errors when any modal is hidden }
// Function to show a flexible custom modal (for general alerts/info) function showFlexibleModal(messageHTML, buttonsConfig, callback = null) { modalMessageDiv.innerHTML = messageHTML; modalButtonsContainer.innerHTML = ''; // Clear previous buttons
if (buttonsConfig && buttonsConfig.length > 0) { const isInline = buttonsConfig.every(btn => !btn.newline); modalButtonsContainer.className = isInline ? 'modal-buttons-inline' : 'modal-buttons-stacked';
buttonsConfig.forEach(btnConf => { const button = document.createElement('button'); button.className = 'modal-button'; button.textContent = btnConf.text; if (btnConf.style) { button.style = btnConf.style; } button.onclick = function() { hideCustomModal(customModal); if (btnConf.action && typeof btnConf.action === 'function') { btnConf.action(); } if (callback && typeof callback === 'function') { callback(); } }; modalButtonsContainer.appendChild(button); }); } else { const okButton = document.createElement('button'); okButton.className = 'modal-button'; okButton.textContent = 'OK'; okButton.onclick = function() { hideCustomModal(customModal); if (callback && typeof callback === 'function') { callback(); } }; modalButtonsContainer.classList.remove('modal-buttons-inline', 'modal-buttons-stacked'); modalButtonsContainer.classList.add('modal-buttons'); modalButtonsContainer.appendChild(okButton); } showCustomModal(customModal); }
// Slide logic function slideToSignup() { if (loginFormDiv && loginText) { loginFormDiv.style.marginLeft = "-50%"; loginText.style.marginLeft = "-50%"; clearErrors('main'); } }
function slideToLogin() { if (loginFormDiv && loginText) { loginFormDiv.style.marginLeft = "0%"; loginText.style.marginLeft = "0%"; clearErrors('main'); } }
// Event listeners for radio buttons and signup link if (signupRadio) { signupRadio.addEventListener('change', function() { if (this.checked) { slideToSignup(); } }); }
if (loginRadio) { loginRadio.addEventListener('change', function() { if (this.checked) { slideToLogin(); } }); }
if (signupLink && signupRadio) { signupLink.onclick = ((e) => { e.preventDefault(); signupRadio.checked = true; slideToSignup(); }); }
// Handle URL parameter for initial tab const urlParams = new URLSearchParams(window.location.search); const showSignup = urlParams.get('signup');
if (showSignup === 'true') { if (signupRadio) { signupRadio.checked = true; slideToSignup(); } } else { if (loginRadio) { loginRadio.checked = true; slideToLogin(); } }
// Function to toggle password visibility function setupPasswordToggle(passwordInput, toggleIcon) { if (passwordInput && toggleIcon) { toggleIcon.addEventListener('click', function() { const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password'; passwordInput.setAttribute('type', type); this.classList.toggle('fa-eye'); this.classList.toggle('fa-eye-slash'); }); } }
// Setup password toggles for all password fields setupPasswordToggle(loginPasswordInput, document.querySelector('#loginForm .toggle-password')); setupPasswordToggle(signupPasswordInput, document.querySelector('#signupForm #signupPassword + .toggle-password')); setupPasswordToggle(signupConfirmPasswordInput, document.querySelector('#signupForm #signupConfirmPassword + .toggle-password')); setupPasswordToggle(newPasswordInput, document.querySelector('#resetPasswordForm #newPassword + .toggle-password')); setupPasswordToggle(confirmNewPasswordInput, document.querySelector('#resetPasswordForm #confirmNewPassword + .toggle-password'));
// Login Form Submission Handler if (loginForm) { loginForm.addEventListener('submit', function(event) { event.preventDefault(); clearErrors('main'); // Clear main form errors
// Only proceed if login attempts are below limit if (loginAttempts >= MAX_LOGIN_ATTEMPTS) { showLoginAttemptsLimitModal(); return; // Stop submission }
let isValid = true;
const usernameOrEmail = loginUsernameOrEmailInput.value.trim(); const password = loginPasswordInput.value.trim();
if (usernameOrEmail === '') { isValid = false; loginUsernameOrEmailError.textContent = 'Username or Email is required'; loginUsernameOrEmailInput.classList.add('error'); } if (password === '') { isValid = false; loginPasswordError.textContent = 'Password is required'; loginPasswordInput.classList.add('error'); }
if (isValid) { submitFormData(event.target, loginSubmitButton, '/api/login', 'main'); } }); }
// Signup Form Submission Handler if (signupForm) { signupForm.addEventListener('submit', function(event) { event.preventDefault(); clearErrors('main');
let isValid = true;
const name = signupNameInput.value.trim(); const email = signupEmailInput.value.trim(); const password = signupPasswordInput.value.trim(); const confirmPassword = signupConfirmPasswordInput.value.trim();
if (name === '') { isValid = false; signupNameError.textContent = 'Name is required'; signupNameInput.classList.add('error'); }
if (email === '') { isValid = false; signupEmailError.textContent = 'Email is required'; signupEmailInput.classList.add('error'); } else if (!isValidEmail(email)) { isValid = false; signupEmailError.textContent = 'Enter a valid email address'; signupEmailInput.classList.add('error'); }
if (password === '') { isValid = false; signupPasswordError.textContent = 'Password is required'; signupPasswordInput.classList.add('error'); } else if (password.length < 6) { isValid = false; signupPasswordError.textContent = 'Password must be at least 6 characters'; signupPasswordInput.classList.add('error'); }
if (confirmPassword === '') { isValid = false; signupConfirmPasswordError.textContent = 'Confirm password is required'; signupConfirmPasswordInput.classList.add('error'); } else if (password !== confirmPassword) { isValid = false; signupConfirmPasswordError.textContent = 'Passwords do not match'; signupConfirmPasswordInput.classList.add('error'); signupPasswordInput.classList.add('error'); }
if (isValid) { submitFormData(event.target, signupSubmitButton, '/api/signup', 'main'); } }); }
// Forgot Password Link Handler (Initial Click) if (forgotPasswordLink) { forgotPasswordLink.addEventListener('click', function(event) { event.preventDefault(); clearErrors('forgot'); // Clear errors for email request clearErrors('otp'); // Clear errors for OTP section
forgotPasswordRequestForm.reset(); // Clear email input otpInput.value = ''; // Clear OTP input // Reset the general message for the forgot password modal forgotModalMessage.innerHTML = 'Enter your registered email to request a password reset.';
// Show the email request form and hide the OTP section forgotPasswordRequestForm.style.display = 'block'; if (otpSection) otpSection.style.display = 'none'; // Ensure OTP section is hidden initially
showCustomModal(forgotPasswordRequestModal); }); }
// Step 1: Forgot Password Request Form Submission Handler (Requests OTP) if (forgotPasswordRequestForm) { forgotPasswordRequestForm.addEventListener('submit', async function(event) { event.preventDefault(); clearErrors('forgot'); // Clear errors specific to the email request form
let isValid = true; const email = forgotEmailInput.value.trim();
if (email === '') { isValid = false; forgotEmailError.textContent = 'Email is required.'; forgotEmailInput.classList.add('error'); } else if (!isValidEmail(email)) { isValid = false; forgotEmailError.textContent = 'Enter a valid email address.'; forgotEmailInput.classList.add('error'); }
if (isValid) { forgotSubmitButton.disabled = true; forgotSubmitButton.innerHTML = '<span class="loading-spinner"></span> Sending OTP...';
try { const response = await fetch('/api/forgot_password_request', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: email }) });
const result = await response.json();
if (response.ok) { currentForgotEmail = email; // Store email for subsequent steps
// Transition to OTP input section forgotPasswordRequestForm.style.display = 'none'; if (otpSection) otpSection.style.display = 'block'; otpInput.value = ''; // Clear previous OTP in case of resend
// Update message for OTP section let messageText = `<p>An OTP has been sent to <strong>${email}</strong>. Please enter it below.</p>`; // Note: Do not display simulated OTP in production. This is for testing convenience. // if (result.simulated_otp) { // messageText += `<p><strong>SIMULATED OTP (FOR TESTING):</strong> ${result.simulated_otp}</p>`; // } forgotModalMessage.innerHTML = messageText;
} else { displayModalFormErrors(result, forgotPasswordRequestForm, 'forgot'); } } catch (error) { console.error('Fetch error:', error); showFlexibleModal('<p>Network error. Could not request OTP. Please try again.</p>', [{ text: 'OK' }]); } finally { forgotSubmitButton.disabled = false; forgotSubmitButton.innerHTML = 'Request OTP'; } } }); }
// Step 2: OTP Verification Form Submission Handler if (verifyOtpForm) { verifyOtpForm.addEventListener('submit', async function(event) { event.preventDefault(); clearErrors('otp'); // Clear errors specific to the OTP verification form
let isValid = true; const otp = otpInput.value.trim();
if (otp === '') { isValid = false; otpError.textContent = 'OTP is required.'; otpInput.classList.add('error'); } else if (!/^\d{6}$/.test(otp)) { // Ensure it's 6 digits isValid = false; otpError.textContent = 'OTP must be a 6-digit number.'; otpInput.classList.add('error'); }
if (isValid) { verifyOtpButton.disabled = true; verifyOtpButton.innerHTML = '<span class="loading-spinner"></span> Verifying...';
try { const response = await fetch('/api/verify_otp', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: currentForgotEmail, otp: otp }) });
const result = await response.json();
if (response.ok) { hideCustomModal(forgotPasswordRequestModal); // Hide the OTP modal resetEmailInput.value = currentForgotEmail; // Pre-fill email in new password form newPasswordInput.value = ''; // Clear new password field confirmNewPasswordInput.value = ''; // Clear confirm new password field showCustomModal(resetPasswordModal); // Show the new password modal
} else { otpError.textContent = result.message || 'OTP verification failed.'; otpInput.classList.add('error'); otpInput.classList.add('error'); // Ensure input field is marked // Update the main message area of the OTP modal if a general message is returned if (result.message) { forgotModalMessage.innerHTML = `<p>${result.message}</p>`; } } } catch (error) { console.error('Fetch error:', error); showFlexibleModal('<p>Network error. Could not verify OTP. Please try again.</p>', [{ text: 'OK' }]); } finally { verifyOtpButton.disabled = false; verifyOtpButton.innerHTML = 'Verify OTP'; } } }); }
// Step 2: Resend OTP Button Handler if (resendOtpButton) { resendOtpButton.addEventListener('click', async function(event) { event.preventDefault(); clearErrors('otp'); // Clear any previous OTP errors resendOtpButton.disabled = true; resendOtpButton.innerHTML = '<span class="loading-spinner"></span> Resending...';
try { const response = await fetch('/api/forgot_password_request', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: currentForgotEmail }) });
const result = await response.json();
if (response.ok) { let messageText = `<p>New OTP sent to <strong>${currentForgotEmail}</strong>. Please enter it below.</p>`; // if (result.simulated_otp) { // Again, remove in production // messageText += `<p><strong>SIMULATED OTP (FOR TESTING):</strong> ${result.simulated_otp}</p>`; // } forgotModalMessage.innerHTML = messageText; otpInput.value = ''; // Clear previous OTP otpInput.classList.remove('error'); // Clear error state otpError.textContent = ''; // Clear error message } else { // If there's an error on resend, display it in the OTP section's error message otpError.textContent = result.message || 'Failed to resend OTP.'; otpInput.classList.add('error'); // Potentially highlight OTP input again if (result.message) { forgotModalMessage.innerHTML = `<p>${result.message}</p>`; } } } catch (error) { console.error('Fetch error:', error); showFlexibleModal('<p>Network error. Could not resend OTP. Please try again.</p>', [{ text: 'OK' }]); } finally { resendOtpButton.disabled = false; resendOtpButton.innerHTML = 'Send Again'; } }); }
// Handlers for Cancel buttons in the forgot/reset modals if (forgotCancelButton) { forgotCancelButton.addEventListener('click', function() { hideCustomModal(forgotPasswordRequestModal); forgotPasswordRequestForm.reset(); currentForgotEmail = ''; // Clear stored email clearErrors('forgot'); // Ensure all forgot-related errors are cleared }); }
if (otpCancelButton) { otpCancelButton.addEventListener('click', function() { hideCustomModal(forgotPasswordRequestModal); verifyOtpForm.reset(); currentForgotEmail = ''; // Clear stored email clearErrors('otp'); // Ensure all OTP-related errors are cleared }); }
if (resetCancelButton) { resetCancelButton.addEventListener('click', function() { hideCustomModal(resetPasswordModal); resetPasswordForm.reset(); currentForgotEmail = ''; // Clear stored email clearErrors('reset'); // Ensure all reset-related errors are cleared }); }
// Step 3: Reset Password Form Submission Handler if (resetPasswordForm) { resetPasswordForm.addEventListener('submit', async function(event) { event.preventDefault(); clearErrors('reset'); // Clear errors specific to the reset password form
let isValid = true; const email = resetEmailInput.value.trim(); // This should be currentForgotEmail const newPassword = newPasswordInput.value.trim(); const confirmNewPassword = confirmNewPasswordInput.value.trim();
if (email === '') { // Should be pre-filled, but a final check isValid = false; resetEmailError.textContent = 'Email is required.'; resetEmailInput.classList.add('error'); } else if (!isValidEmail(email)) { isValid = false; resetEmailError.textContent = 'Invalid email format.'; // Should not happen if pre-filled correctly resetEmailInput.classList.add('error'); }
if (newPassword === '') { isValid = false; newPasswordError.textContent = 'New password is required.'; newPasswordInput.classList.add('error'); } else if (newPassword.length < 6) { isValid = false; newPasswordError.textContent = 'New password must be at least 6 characters.'; newPasswordInput.classList.add('error'); }
if (confirmNewPassword === '') { isValid = false; confirmNewPasswordError.textContent = 'Confirm new password is required.'; confirmNewPasswordInput.classList.add('error'); } else if (newPassword !== confirmNewPassword) { isValid = false; confirmNewPasswordError.textContent = 'Passwords do not match.'; confirmNewPasswordInput.classList.add('error'); newPasswordInput.classList.add('error'); // Highlight both if they don't match }
if (isValid) { resetSubmitButton.disabled = true; resetSubmitButton.innerHTML = '<span class="loading-spinner"></span> Resetting...';
try { const response = await fetch('/api/reset_password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: email, new_password: newPassword }) // Ensure correct variable name for new password });
const result = await response.json();
if (response.ok) { hideCustomModal(resetPasswordModal); resetPasswordForm.reset(); currentForgotEmail = ''; // Clear stored email after successful reset showFlexibleModal( '<p>Password reset successful. You can now login with your new password.</p>', [{ text: 'OK', action: () => { loginRadio.checked = true; slideToLogin(); }}] ); } else { // Display error messages from the backend displayModalFormErrors(result, resetPasswordForm, 'reset'); if (result.message && (result.message.includes('OTP not verified') || result.message.includes('not initiated'))) { showFlexibleModal( `<p>${result.message}</p><p>Please start the password reset process again.</p>`, [{ text: 'Start Over', action: () => { hideCustomModal(resetPasswordModal); forgotPasswordLink.click(); // Re-open the initial forgot password modal }}], null // No general callback ); } } } catch (error) { console.error('Fetch error:', error); showFlexibleModal('<p>Network error. Could not reset password. Please try again.</p>', [{ text: 'OK' }]); } finally { resetSubmitButton.disabled = false; resetSubmitButton.innerHTML = 'Reset Password'; } } }); }
// This function handles displaying errors from the backend for the main login/signup forms function handleMainFormErrors(result, formElement, endpoint) { if (endpoint === '/api/login') { if (result.message && (result.message.includes('Account not found') || result.message.includes('Invalid credentials'))) { showFlexibleModal( `<p>${result.message}</p><p>If you are not registered, please sign up.</p>`, [{ text: 'Sign Up', action: () => { signupRadio.checked = true; slideToSignup(); }}, { text: 'OK', style: 'background-color: var(--bs-secondary-color);' }] ); } } else if (endpoint === '/api/signup') { if (result.message && (result.message.includes('Email already registered') || result.message.includes('Username already taken'))) { showFlexibleModal( `<p>${result.message}</p><p>If you are already registered, please log in.</p>`, [{ text: 'Login', action: () => { loginRadio.checked = true; slideToLogin(); }}, { text: 'OK', style: 'background-color: var(--bs-secondary-color);' }] ); } } if (result.errors) { for (const field in result.errors) { let inputElement, errorElement;
if (formElement.id === 'loginForm' && field === 'username_or_email') { inputElement = loginUsernameOrEmailInput; errorElement = loginUsernameOrEmailError; } else if (formElement.id === 'signupForm' && field === 'name') { inputElement = signupNameInput; errorElement = signupNameError; } else { // This handles password errors for login and email/password for signup // Need to be careful with field names. Example: if backend returns 'password' for signup. inputElement = formElement.querySelector(`[name="${field}"]`); // This assumes predictable error element IDs based on input IDs const inputId = inputElement ? inputElement.id : null; errorElement = inputId ? document.getElementById(`${inputId}Error`) : null; }
if (errorElement) errorElement.textContent = result.errors[field]; if (inputElement) inputElement.classList.add('error'); } } }
// Generic function for handling errors in modals (forgot, otp, reset) function displayModalFormErrors(result, formElement, formContext) { // Clear errors specific to the current modal's form context clearErrors(formContext);
if (result.errors) { for (const field in result.errors) { // This is robust: Find the input element by its 'name' attribute const inputElement = formElement.querySelector(`[name="${field}"]`); // Then, find its associated error message element by looking for a sibling with the ID pattern const errorElement = inputElement ? document.getElementById(`${inputElement.id}Error`) : null;
if (errorElement) errorElement.textContent = result.errors[field]; if (inputElement) inputElement.classList.add('error'); } } // Update the main message area of the modal if a general message is returned const targetModalMessage = formElement.closest('.modal-content').querySelector('.modal-message'); if (targetModalMessage && result.message) { targetModalMessage.innerHTML = `<p>${result.message}</p>`; } }
// Main data submission function (unchanged for main forms, adapted for modals) async function submitFormData(formElement, submitButton, endpoint, formContext) { if (!formElement || !submitButton || !endpoint) { console.error("submitFormData called with missing arguments."); return; }
const formData = new FormData(formElement); const data = {}; for (let [key, value] of formData.entries()) { data[key] = value; }
submitButton.disabled = true; if (formContext === 'main') { displayFormMessage("Submitting...", 'info'); } else { // For modal buttons, update their innerHTML directly submitButton.innerHTML = '<span class="loading-spinner"></span> Submitting...'; }
try { const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), });
const result = await response.json();
if (response.ok) { if (formContext === 'main') { clearErrors('main'); formElement.reset(); displayFormMessage('', 'info'); // Clear "Submitting..." message loginAttempts = 0; // Reset login attempts on successful login
if (endpoint === '/api/signup') { showFlexibleModal( '<p>Registration successful! Please log in.</p>', [{ text: 'OK', action: () => { loginRadio.checked = true; slideToLogin(); const url = new URL(window.location); url.searchParams.delete('signup'); // Clean up URL window.history.replaceState({}, '', url.toString()); }}] ); } else if (endpoint === '/api/login') { showFlexibleModal( '<p>Login successful!</p>', [{ text: 'OK', action: () => { // Mark user as logged in so chat.html knows localStorage.setItem('gakr_is_logged_in', 'true'); alert('Welcome! You are logged in.'); // Optional: remove any guest flag if you had one // localStorage.removeItem('gakr_is_guest');
// Redirect back to chat interface window.location.href = 'chat.html'; } }] );}
} // For forgot/otp/reset, successful handling is now done directly in their respective event listeners // so no generic handling here for those contexts. } else { // Server returned an error (response.ok is false) if (formContext === 'main') { if (endpoint === '/api/login' && result.message && result.message.includes('Invalid credentials')) { loginAttempts++; loginPasswordInput.classList.add('error'); loginPasswordError.textContent = result.message;
if (loginAttempts >= MAX_LOGIN_ATTEMPTS) { showLoginAttemptsLimitModal(); loginPasswordInput.value = ''; // Clear password after max attempts } else { displayFormMessage(`Incorrect password. You have ${MAX_LOGIN_ATTEMPTS - loginAttempts} attempts left.`, 'error'); } } else { displayFormMessage(result.message || 'An error occurred.', 'error'); handleMainFormErrors(result, formElement, endpoint); } } else if (formContext === 'forgot') { displayModalFormErrors(result, formElement, 'forgot'); } else if (formContext === 'otp') { displayModalFormErrors(result, formElement, 'otp'); } else if (formContext === 'reset') { displayModalFormErrors(result, formElement, 'reset'); } } } catch (error) { console.error('Fetch error:', error); if (formContext === 'main') { displayFormMessage('Network error. Please try again.', 'error'); } else { showFlexibleModal( '<p>Network error. Please check your internet connection and try again.</p>', [{ text: 'OK' }] ); } } finally { submitButton.disabled = false; // Reset button text specifically for modal forms if not handled by success/error flows above if (formContext === 'forgot') { submitButton.innerHTML = 'Request OTP'; } else if (formContext === 'otp') { submitButton.innerHTML = 'Verify OTP'; } else if (formContext === 'reset') { submitButton.innerHTML = 'Reset Password'; } } }
function showLoginAttemptsLimitModal() { const messageHtml = ` <strong>You have made three incorrect login attempts.</strong> <ul> <li>1. If you are not registered, please <a href="#" id="modalSignupLink">sign up now</a>.</li> <li>2. If you are already registered, please <a href="#" id="modalLoginLink">login now</a> with correct credentials.</li> <li>3. If you have forgotten your password, click <a href="#" id="modalForgotPasswordLink">forgot password</a> to reset it.</li> </ul> `; const buttons = [ { text: 'Login', action: () => { loginRadio.checked = true; slideToLogin(); loginAttempts = 0; loginPasswordInput.value = ''; }}, { text: 'Signup', action: () => { signupRadio.checked = true; slideToSignup(); loginAttempts = 0; loginPasswordInput.value = ''; }} ];
showFlexibleModal(messageHtml, buttons, () => { const modalSignupLink = document.getElementById('modalSignupLink'); const modalLoginLink = document.getElementById('modalLoginLink'); const modalForgotPasswordLink = document.getElementById('modalForgotPasswordLink');
if (modalSignupLink) { modalSignupLink.onclick = (e) => { e.preventDefault(); hideCustomModal(customModal); signupRadio.checked = true; slideToSignup(); loginAttempts = 0; loginPasswordInput.value = ''; }; } if (modalLoginLink) { modalLoginLink.onclick = (e) => { e.preventDefault(); hideCustomModal(customModal); loginRadio.checked = true; slideToLogin(); loginAttempts = 0; loginPasswordInput.value = ''; }; } if (modalForgotPasswordLink) { modalForgotPasswordLink.onclick = (e) => { e.preventDefault(); hideCustomModal(customModal); forgotPasswordLink.click(); loginAttempts = 0; loginPasswordInput.value = ''; }; } }); }
function isValidEmail(email) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); } });</script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397#!/usr/bin/env python3
"""
file_pipeline.py
Universal file pipeline for GAKR AI.
Responsibilities:
- Create dataupload/ folder structure (if not present)
- Save uploaded files to disk
- Detect file type
- Run type-specific extractors
- Return structured, text-friendly context for Phi-3
"""
from __future__ import annotations
import os
import mimetypes
from datetime import datetime
from typing import List, Dict, Any
import pandas as pd
import pdfplumber
import docx
import fitz # PyMuPDF
from PIL import Image
import pytesseract
import whisper
import ffmpeg
from fastapi import UploadFile
# ============================================================
# PATHS & FOLDERS
# ============================================================
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
UPLOAD_ROOT = os.path.join(BASE_DIR, "dataupload")
FOLDERS = {
"image": "images",
"video": "videos",
"audio": "audio",
"document": "documents",
"tabular": "tabular",
"other": "other",
}
def ensure_folders() -> None:
"""
Ensure base upload folder and all subfolders exist.
"""
os.makedirs(UPLOAD_ROOT, exist_ok=True)
for sub in FOLDERS.values():
os.makedirs(os.path.join(UPLOAD_ROOT, sub), exist_ok=True)
ensure_folders()
# ============================================================
# TYPE DETECTION & PATHS
# ============================================================
def detect_kind(filename: str, content_type: str | None) -> str:
"""
Decide logical kind: tabular, document, image, audio, video, other.
"""
ext = os.path.splitext(filename)[1].lower()
if ext in [".csv", ".xlsx", ".xls", ".json"]:
return "tabular"
if ext in [".pdf", ".txt"]:
return "document"
if ext in [".docx"]:
return "document"
if ext in [".png", ".jpg", ".jpeg", ".webp", ".bmp"]:
return "image"
if ext in [".mp3", ".wav", ".m4a"]:
return "audio"
if ext in [".mp4", ".mkv", ".mov", ".avi"]:
return "video"
if content_type:
if content_type.startswith("image/"):
return "image"
if content_type.startswith("audio/"):
return "audio"
if content_type.startswith("video/"):
return "video"
return "other"
def make_target_path(kind: str, filename: str) -> str:
"""
Build a safe, timestamped filepath under dataupload/{sub}/.
"""
sub = FOLDERS.get(kind, "other")
safe_name = os.path.basename(filename)
timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S_%f")
final_name = f"{timestamp}_{safe_name}"
return os.path.join(UPLOAD_ROOT, sub, final_name)
# ============================================================
# MAIN MULTI-FILE ENTRY POINT
# ============================================================
async def process_files(files: List[UploadFile]) -> Dict[str, Any]:
"""
Save all files, run analyses, and return structured context.
Output example:
{
"files": [
{
"original_name": "...",
"stored_path": "dataupload/documents/...",
"kind": "document",
"summary": { ... }
},
...
]
}
"""
ensure_folders()
results: List[Dict[str, Any]] = []
for uf in files:
try:
kind = detect_kind(uf.filename, uf.content_type)
target_path = make_target_path(kind, uf.filename)
# Save file to disk
try:
with open(target_path, "wb") as out:
data = await uf.read()
out.write(data)
except Exception as save_err:
results.append(
{
"original_name": uf.filename,
"stored_path": None,
"kind": kind,
"summary": {
"error": f"Failed to save file: {save_err}"
},
}
)
continue
# Analyze by type
try:
summary = analyze_file(target_path, kind)
except Exception as analyze_err:
summary = {
"error": f"Unexpected error in analysis: {analyze_err}"
}
results.append(
{
"original_name": uf.filename,
"stored_path": os.path.relpath(target_path, BASE_DIR),
"kind": kind,
"summary": summary,
}
)
except Exception as outer_err:
results.append(
{
"original_name": getattr(uf, "filename", "unknown"),
"stored_path": None,
"kind": "unknown",
"summary": {
"error": f"Fatal error while handling file: {outer_err}"
},
}
)
return {"files": results}
# ============================================================
# TYPE-SPECIFIC ANALYSIS
# ============================================================
def analyze_file(path: str, kind: str) -> Dict[str, Any]:
if kind == "tabular":
return analyze_tabular(path)
if kind == "document":
return analyze_document(path)
if kind == "image":
return analyze_image(path)
if kind == "audio":
return analyze_audio(path)
if kind == "video":
return analyze_video(path)
return {"type": "other", "note": "Unsupported or unknown file type"}
# ---------- TABULAR: CSV / Excel / JSON ----------
def analyze_tabular(path: str) -> Dict[str, Any]:
ext = os.path.splitext(path)[1].lower()
df = None
try:
if ext == ".csv":
df = pd.read_csv(path)
elif ext in [".xlsx", ".xls"]:
df = pd.read_excel(path)
elif ext == ".json":
df = pd.read_json(path)
else:
return {
"type": "tabular",
"error": f"Unsupported tabular format: {ext}",
}
except Exception as e:
return {"type": "tabular", "error": f"Failed to load table: {e}"}
summary: Dict[str, Any] = {
"type": "tabular",
"rows": int(df.shape[0]),
"columns": [str(c) for c in df.columns],
}
try:
summary["missing_values"] = df.isna().sum().to_dict()
except Exception as e:
summary["missing_values_error"] = str(e)
try:
summary["numeric_stats"] = df.describe(include="number").to_dict()
except Exception:
summary["numeric_stats"] = {}
return summary
# ---------- DOCUMENTS: PDF / DOCX / TXT ----------
def analyze_document(path: str) -> Dict[str, Any]:
ext = os.path.splitext(path)[1].lower()
text = ""
try:
if ext == ".pdf":
# First try pdfplumber
try:
with pdfplumber.open(path) as pdf:
pages = []
for page in pdf.pages[:10]:
t = page.extract_text()
if t:
pages.append(t)
text = "\n".join(pages)
except Exception:
# Fallback to PyMuPDF
doc = fitz.open(path)
chunks = []
for page in doc[:10]:
chunks.append(page.get_text())
text = "\n".join(chunks)
elif ext == ".docx":
d = docx.Document(path)
paras = [p.text for p in d.paragraphs if p.text.strip()]
text = "\n".join(paras)
else: # .txt or unknown plain-text
with open(path, "r", encoding="utf-8", errors="ignore") as f:
text = f.read()
except Exception as e:
return {
"type": "document",
"error": f"Failed to extract document text: {e}",
}
short = text[:4000]
return {
"type": "document",
"char_count": len(text),
"preview": short,
}
# ---------- IMAGES ----------
def analyze_image(path: str) -> Dict[str, Any]:
try:
img = Image.open(path)
except Exception as e:
return {"type": "image", "error": f"Failed to open image: {e}"}
try:
text = pytesseract.image_to_string(img)
except Exception as e:
text = ""
ocr_error = str(e)
else:
ocr_error = None
short = text[:2000]
result: Dict[str, Any] = {
"type": "image",
"size": {"width": img.width, "height": img.height},
"ocr_preview": short,
}
if ocr_error:
result["ocr_error"] = ocr_error
return result
# ---------- AUDIO (Whisper) ----------
_whisper_model = None
def get_whisper_model():
global _whisper_model
if _whisper_model is None:
try:
_whisper_model = whisper.load_model("small")
except Exception as e:
raise RuntimeError(f"Failed to load Whisper model: {e}")
return _whisper_model
def analyze_audio(path: str) -> Dict[str, Any]:
try:
model = get_whisper_model()
except Exception as e:
return {"type": "audio", "error": str(e)}
try:
result = model.transcribe(path)
except Exception as e:
return {"type": "audio", "error": f"Whisper transcription failed: {e}"}
text = result.get("text", "") or ""
short = text[:4000]
duration = None
try:
if result.get("segments"):
duration = result["segments"][-1].get("end", None)
except Exception:
duration = None
return {
"type": "audio",
"duration_sec": duration,
"transcript_preview": short,
}
# ---------- VIDEO (audio extraction + Whisper) ----------
def analyze_video(path: str) -> Dict[str, Any]:
audio_path = path + ".tmp_audio.wav"
audio_summary: Dict[str, Any]
try:
(
ffmpeg
.input(path)
.output(audio_path, ac=1, ar=16000)
.overwrite_output()
.run(quiet=True)
)
except Exception as e:
return {
"type": "video",
"error": f"Failed to extract audio from video: {e}",
}
try:
audio_summary = analyze_audio(audio_path)
finally:
try:
if os.path.exists(audio_path):
os.remove(audio_path)
except Exception:
pass
return {
"type": "video",
"audio_analysis": audio_summary,
}auth.htmlAdded+1510
file_pipeline.pyAdded+397