Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
asilvafx authored Nov 16, 2023
1 parent ea54409 commit 5ae5a0c
Show file tree
Hide file tree
Showing 4 changed files with 348 additions and 0 deletions.
Binary file added favicon.ico
Binary file not shown.
85 changes: 85 additions & 0 deletions index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenAI Whisper API</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<style>
.recording-controls {
background-color: #2b2b3a;
border-radius: 10px;
padding: 15px;
color: #1ed2f4;
margin-bottom: 20px;
}
.recording-controls button {
background-color: #eafc40;
border: none;
border-radius: 5px;
padding: 10px 15px;
margin-right: 10px;
color: #254558;
}
.recording-controls audio {
display: block;
margin-top: 10px;
}
.row {
display: flex;
}
.col-4 {
flex: 1;
}
.col-8 {
flex: 2;
padding-left: 20px;
}
.whisper_response_display_area {
padding: 15px;
border: 1px solid #1ed2f4;
border-radius: 5px;
color: #f4f5f6;
background-color: #254558;
}
</style>
</head>
<body>
<div class="container mt-4">
<div class="recording-controls">
<div class="row">
<div class="col-4">
<button id="start">Start recording</button>
<button id="stop" disabled>Stop recording</button>
<audio id="audio" controls class="d-none"></audio>
<form class="mt-4" enctype="multipart/form-data" id="audio_form" method="post" action="whisper_send_data.php">
<input type="file" name="audio" accept=".ogg,.flac,.mp3,.wav" required/>
<input type="submit" id="fileUpload" name="submit"/>
<span id="fileUploading" class="mt-2" style="display: none;">Loading..</span>
</form>
</div>
<div class="col-8">
<p class="whisper_response_display_area" id="whisper_response_display_area"></p>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lamejs/1.2.0/lame.min.js"></script>
<script src="input.js"></script>
</body>
</html>
153 changes: 153 additions & 0 deletions input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// ------------------------------------------------------------------------------------------------------------------------
//
// Description: OpenAI Whisper API
// Author: PIGMIL
// Website: https://pigmil.com
//
// ------------------------------------------------------------------------------------------------------------------------

let chunks = [];
let mediaRecorder;

let startButton = document.getElementById("start");
let stopButton = document.getElementById("stop");
let audioForm = document.getElementById("audio_form");


// Initial state
stopButton.style.backgroundColor = "#2b2b3a"; // Gray color
stopButton.disabled = true;

function getRequest(){
let blob = new Blob(chunks, { type: "audio/webm" });
chunks = [];
let audioURL = URL.createObjectURL(blob);
document.getElementById("audio").src = audioURL;

// Create a new FormData object.
var formData = new FormData();

// Create a blob file object from the blob.
var file = new File([blob], Math.floor(1000 + Math.random() * 9000)+".webm", {
type: "audio/webm",
});

// Append the audio file to the form data.
formData.append("audio", file);

console.log("Sending audio file to server...");

// Send the audio file to your server.
fetch("whisper_send_data.php", {
method: "POST",
body: formData,
})
.then((response) => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}

return response.text(); // Return the response as text
})
.then((data) => {
// Process the response here
let whisper_received_data = JSON.parse(data);
HandleRequest(whisper_received_data.text);

})
.catch(function (error) {
console.error("Error sending audio file to server:", error);
return false;
});

return false;
}

function HandleRequest(prompt){

console.log("Sending transcription to server...");
console.log(prompt);
document.getElementById("whisper_response_display_area").textContent =
prompt;

return false;
}

audioForm.addEventListener("submit", function(e) {
e.preventDefault();

const form = e.currentTarget;
const formData = new FormData(form);

var fileUpload = document.getElementById('fileUpload');
var fileUploading = document.getElementById('fileUploading');

fileUpload.style.display = "none";
fileUploading.style.display = "block";

console.log("Sending audio file to server...");

// Send the audio file to your server.
fetch("whisper_send_data.php", {
method: "POST",
body: formData,
})
.then((response) => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}

return response.text(); // Return the response as text
})
.then((data) => {
// Process the response here
let whisper_received_data = JSON.parse(data);
HandleRequest(whisper_received_data.text);
fileUpload.style.display = "block";
fileUploading.style.display = "none";

})
.catch(function (error) {
console.error("Error sending audio file to server:", error);
fileUpload.style.display = "block";
fileUploading.style.display = "none";
return false;
});

});

startButton.addEventListener("click", () => {
navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
mediaRecorder = new MediaRecorder(stream, { mimeType: "audio/webm" });
mediaRecorder.start();

startButton.style.backgroundColor = "#2b2b3a"; // Gray color
startButton.disabled = true;

stopButton.style.backgroundColor = "#1ed2f4"; // Main color
stopButton.disabled = false;

mediaRecorder.ondataavailable = (e) => {
chunks.push(e.data);
};

mediaRecorder.onstop = (e) => {
getRequest();
};

console.log("Recording started...");
});
});

stopButton.addEventListener("click", () => {
if (mediaRecorder) {
mediaRecorder.stop();
}
console.log("Recording stopped...");

stopButton.style.backgroundColor = "#2b2b3a"; // Gray color
stopButton.disabled = true;

startButton.style.backgroundColor = "#1ed2f4"; // Main color
startButton.disabled = false;
});
110 changes: 110 additions & 0 deletions whisper_send_data.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php
// ------------------------------------------------------------------------------------------------------------------------
//
// Description: OpenAI Whisper API
// Author: PIGMIL
// Website: https://pigmil.com
//
// ------------------------------------------------------------------------------------------------------------------------

// Start Server Session
session_start();

define('OPENAI_API_KEY', 'sk-YOUR_OPENAI_API_KEY');

// Path to the directory you want to save the files
$target_dir = "./tmp/";
// List of file extention to be accepted
$valid_formats1 = array("mp3", "ogg", "flac", "wav");

// Check if file is uploaded
if(isset($_POST['submit']) || isset($_FILES["audio"]["name"])) {
if(isset($_POST['submit']))
{
$file1 = $_FILES['audio']['name']; //input file name in this code is file1
$size = $_FILES['audio']['size'];

if(strlen($file1))
{
list($txt, $ext) = explode(".", $file1);
if(in_array($ext,$valid_formats1))
{
$actual_file_name = time().'-'.rand(1000,9999).".".$ext;
$tmp = $_FILES['audio']['tmp_name'];
if(move_uploaded_file($tmp, $target_dir.$actual_file_name))
{
//success upload
$target_file = $target_dir.$actual_file_name;
}
else {
echo "Failed to upload file. Try again later.";
return false;
exit();
}
}
}
} else {
// Prepare the file path
$target_file = $target_dir . time().'-'. basename($_FILES["audio"]["name"]);

// Move the uploaded file to your target directory
if (move_uploaded_file($_FILES["audio"]["tmp_name"], $target_file)) {
//echo "The file ". basename( $_FILES["audio"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
return false;
exit();
}

}

// Prepare the headers
$headers = [
'Authorization: Bearer ' . OPENAI_API_KEY,
];

// Create a CURLFile object / preparing the image for upload
$cfile = new CURLFile($target_file);

// Initialize the cURL session
$ch = curl_init();

// Set the URL
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/audio/transcriptions');

// Set the request method to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Set the headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Prepare the request body with the file and model
$data = [
'file' => $cfile,
'model' => 'whisper-1',
];

// Set the request body
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Set option to return the result instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the cURL request and get the response
$response = curl_exec($ch);

// Check if any error occurred during the request
if(curl_errno($ch)){
echo 'Request Error:' . curl_error($ch);
}

// Close the cURL session
curl_close($ch);

// Output the response
$_SESSION['whisper_response'] = $response;
echo $response;

} else {
echo "No file was uploaded.";
}

0 comments on commit 5ae5a0c

Please sign in to comment.