Created
May 4, 2022 15:57
-
-
Save vipertechofficial/2ab1129fb98f063e261341749fe87953 to your computer and use it in GitHub Desktop.
Use cloudflare and base64 to work with deepAI image processing easily without having to use the API-KEY in client-side...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// CLIENT-SIDE | |
function postJSON(url, payload, callback_function, content_type = "application/x-www-form-urlencoded") { | |
// This function is required because JSON is weird with some char | |
function clean_json_text(json_text) { | |
json_text = json_text.replace(/\\n/g, "\\n") | |
.replace(/\\'/g, "\\'") | |
.replace(/\\"/g, '\\"') | |
.replace(/\\&/g, "\\&") | |
.replace(/\\r/g, "\\r") | |
.replace(/\\t/g, "\\t") | |
.replace(/\\b/g, "\\b") | |
.replace(/\\f/g, "\\f"); | |
// remove non-printable and other non-valid JSON chars | |
json_text = json_text.replace(/[\u0000-\u0019]+/g,""); | |
return json_text; | |
} | |
let headers = new Headers(); | |
headers.append("Content-Type", content_type); | |
let bodyencoded = content_type === "multipart/form-data" ? new FormData(): new URLSearchParams(); | |
Object.entries(payload).forEach((entry) => { | |
const [key, value] = entry; | |
bodyencoded.append(key, value); | |
}); | |
let request_options = { | |
method: "POST", | |
redirect: "follow", | |
headers: headers, | |
body: content_type === "application/text" ? payload: content_type === "application/json" ? clean_json_text(JSON.stringify(payload)): bodyencoded, | |
}; | |
fetch(url, request_options) | |
.then(response => response.text()) | |
.then(result => callback_function(null, result)) | |
.catch(error => callback_function(error, null)); | |
} | |
function get_base64(file) { | |
return new Promise((resolve, reject) => { | |
const reader = new FileReader(); | |
reader.addEventListener("load", () => resolve(reader.result)); | |
reader.addEventListener("error", () => reject(error)); | |
reader.readAsDataURL(file); | |
}); | |
}; | |
let file = event.target.files[0] || event.path[0].files[0]; | |
get_base64(file).then((base64_in) => { | |
postJSON("https://deepai.pixa-pics.workers.dev/colorizer", base64_in, (err, base64_out) => {console.log(err, base64_out)}, "application/text"); | |
} | |
// CLOUDFLARE SIDE | |
function base64Encode (buf) { | |
let string = ''; | |
(new Uint8Array(buf)).forEach( | |
(byte) => { string += String.fromCharCode(byte) } | |
) | |
return btoa(string) | |
} | |
function base64Decode (string) { | |
string = atob(string); | |
const | |
length = string.length, | |
buf = new ArrayBuffer(length), | |
bufView = new Uint8Array(buf); | |
for (var i = 0; i < length; i++) { bufView[i] = string.charCodeAt(i) } | |
return buf | |
} | |
function clean_json_text(json_text) { | |
json_text = json_text.replace(/\\n/g, "\\n") | |
.replace(/\\'/g, "\\'") | |
.replace(/\\"/g, '\\"') | |
.replace(/\\&/g, "\\&") | |
.replace(/\\r/g, "\\r") | |
.replace(/\\t/g, "\\t") | |
.replace(/\\b/g, "\\b") | |
.replace(/\\f/g, "\\f"); | |
// remove non-printable and other non-valid JSON chars | |
json_text = json_text.replace(/[\u0000-\u0019]+/g,""); | |
return json_text; | |
} | |
function handleOptions(request) { | |
// Make sure the necessary headers are present | |
// for this to be a valid pre-flight request | |
let headers = request.headers; | |
if ( | |
headers.get("Origin") !== null && | |
headers.get("Access-Control-Request-Method") !== null && | |
headers.get("Access-Control-Request-Headers") !== null | |
){ | |
// Handle CORS pre-flight request. | |
// If you want to check or reject the requested method + headers | |
// you can do that here. | |
let respHeaders = { | |
...{ | |
"Access-Control-Allow-Origin": "*", | |
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS", | |
"Access-Control-Max-Age": "86400", | |
}, | |
// Allow all future content Request headers to go back to browser | |
// such as Authorization (Bearer) or X-Client-Name-Version | |
"Access-Control-Allow-Headers": request.headers.get("Access-Control-Request-Headers"), | |
} | |
return new Response(null, { | |
headers: respHeaders, | |
}) | |
} | |
else { | |
// Handle standard OPTIONS request. | |
// If you want to allow other HTTP Methods, you can do that here. | |
return new Response(null, { | |
headers: { | |
Allow: "GET, HEAD, POST, OPTIONS", | |
}, | |
}) | |
} | |
} | |
addEventListener("fetch", (event) => { | |
let request = event.request; | |
event.respondWith( | |
handleRequest(request).catch( | |
(err) => new Response(err.stack, { status: 500 }) | |
) | |
); | |
}); | |
function fix_headers(headers, event_request) { | |
const isOPTIONS = (event_request.method == "OPTIONS"); | |
headers.set("Access-Control-Allow-Origin", event_request.headers.get("Origin")); | |
if (isOPTIONS) { | |
headers.set("Access-Control-Allow-Methods", event_request.headers.get("access-control-request-method")); | |
acrh = event_request.headers.get("access-control-request-headers"); | |
if (acrh) { | |
headers.set("Access-Control-Allow-Headers", acrh); | |
} | |
headers.delete("X-Content-Type-Options"); | |
} | |
return headers; | |
} | |
function build_response(body, params, event_request) { | |
const isOPTIONS = (event_request.method == "OPTIONS"); | |
if (isOPTIONS) { | |
body = null; | |
} | |
var init = { | |
headers: fix_headers(params.headers, event_request), | |
status: (isOPTIONS ? 200 : 200), | |
statusText: (isOPTIONS ? "OK" : "OK") | |
}; | |
return new Response(body, init); | |
} | |
async function handleRequest(request) { | |
const url = new URL(request.url); | |
let { pathname } = url; | |
pathname = decodeURI(pathname); | |
if(request.method == "OPTIONS") { | |
return build_response(null, {headers: new Headers()}, request); | |
}else if (pathname.startsWith("/colorizer") || pathname.startsWith("/waifu2x")) { | |
let headers = new Headers(); | |
//headers.append("Content-Type", "multipart/form-data"); | |
headers.append("Api-Key", "000000000-0000-00000-0000-000000000000"); // ADD YOUR API-KEY HERE | |
headers.append("Accept", "application/json, text/plain, */*",); | |
headers.append("client-library", "deepai-js-client"); | |
console.log(request.body) | |
const img_base64 = await request.text(); | |
const payload = {image: img_base64}; | |
let bodyencoded = new FormData(); | |
Object.entries(payload).forEach((entry) => { | |
const [key, value] = entry; | |
bodyencoded.append(key, value); | |
}); | |
const request_url = pathname.startsWith("/colorizer") ? "https://api.deepai.org/api/colorizer": "https://api.deepai.org/api/waifu2x"; | |
const request_options = { | |
method: "POST", | |
headers: headers, | |
body: bodyencoded, | |
}; | |
const response = await fetch(request_url, request_options); | |
const response_text = await response.text(); | |
const response_img_url = JSON.parse(response_text).output_url; | |
const upstream_img_response = await fetch(response_img_url); | |
const response_img_base64 = "data:image/jpg;base64," + base64Encode(await upstream_img_response.arrayBuffer()); | |
return build_response(response_img_base64, { | |
headers: new Headers({ | |
"Content-Type": "application/text" | |
}), | |
}, request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment