Sorry if this is a simple problem but I'm new to this stuff.
İ have my code below, but the API returns saying İ don't have the right API key put it.
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
async function test() {
const response = await openai.createCompletion("text-davinci-002", {
prompt: "Summarize this for a college student:\n\nJupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter.[19] When viewed from Earth, Jupiter can be bright enough for its reflected light to cast visible shadows,[20] and is on average the third-brightest natural object in the night sky after the Moon and Venus.",
temperature: 0.7,
max_tokens: 64,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
console.log(response)
}
test()
the API key seems to be found in a process.env file that İ don't have, and when İ made a file named process.env and made a variable called OPENAI_API_KEY, but it didn't seem to work. It returns something when İ set apiKey equal to the actual key, but that seems like a roundabout solution. Thanks
process.env is not a folder, it is used to get an environment variable from the host OS. You can simply replace process.env.OPENAI_API_KEY with "your-api-key-here"
process.env is most commonly used when publishing to something like github where you need to keep your api keys secret so that nobody else can use them but so that you can still use them when deploying
Related
Playing around with growthbook, and having a hard time, figuring out how to use experiments.
created experiment.
created feature, with experiment rule
now my feature has variations, and my experiment have variations.
in JS-Land, i do something like:
const growthbook = new GrowthBook({
apiHost: "http://localhost:3100",
clientKey: "sdk-ZzfdzxSSDuHgmpXG",
enableDevMode: true,
trackingCallback: (experiment, result) => {
console.log("Viewed Experiment", {
experimentId: experiment.key,
variationId: result.variationId
});
}
});
growthbook.setAttributes({
user_id: "ccc",
id: "cccc"
});
await growthbook.loadFeatures({ autoRefresh: true });
if (growthbook.isOn("my-test")) {
console.log("Feature is enabled!");
}
it works, but in fact the variationId in the console.log is actually the variation ID of the Feature itself.
question: how to get the variation id of the experiment, or what is the best way to run a experiment.
not quiet sure, how to trigger experiments, and how they are connected. (i understand, metric tracking and conversion tracking - but that requires to get the variationId)
or is it supposed to be - that variationId's on feature need to be done too on experiment?!
My extension has a context menu with items. What I'd like it to do: is when I right-click an editable html element (eg input or textarea) and then select and click on an item in my menu - some value defined by my extension gets entered into the input.
For now I have realised that with document.activeElement.value = myValue.
With simple inputs it works alright.
Problems start when there is an input with custom onChange event handling, eg a calendar or a phone input, or currency input - that transforms user-input in some way.
Since I am setting a value directly onto the element - the handling logic gets omitted, which causes all manner of problems.
Since javascript doesn't allow for KeySend-like features - what are my options here?
I have thought about testing tools like Puppeteer or Cypress - but they all seem not to be packageable into an extension. Puppeteer does have such an option, but it still requires a node instance running to connect to. And I would like my extension to be solely client-sided and distributed in Chrome webstore - so I cannot ask my users to spin up a node server.
There is a built-in DOM method document.execCommand.
In case of an extension, use this code in the content script.
// some.selector may be `input` or `[contenteditable]` for richly formatted inputs
const el = document.querySelector('some.selector');
el.focus();
document.execCommand('insertText', false, 'new text');
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
It imitates physical user input into the currently focused DOM element so all the necessary events will be fired (like beforeinput, input) with isTrusted field set to true. On some pages the change event should be additionally dispatched as shown above.
You may want to select the current text to replace it entirely instead of appending:
replaceValue('some.selector', 'new text');
function replaceValue(selector, value) {
const el = document.querySelector(selector);
if (el) {
el.focus();
el.select();
if (!document.execCommand('insertText', false, value)) {
// Fallback for Firefox: just replace the value
el.value = 'new text';
}
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
}
return el;
}
Note that despite execCommand being marked as obsolete in 2020, it'll work in the foreseeable future because a new editing API specification is not finished yet, and knowing how slow such things usually move it may take another 5-20 years.
#wOxxOm, thank you very much !
I used your code solved my problem which has bothered me for long time. I googled many code and article for nearly one month.
It works on Facebook and many strong website.
Because execCommand has depredated, I try below code it works well, include Facebook.
function imitateKeyInput(el, keyChar) {
if (el) {
const keyboardEventInit = {bubbles:false, cancelable:false, composed:false, key:'', code:'', location:0};
el.dispatchEvent(new KeyboardEvent("keydown", keyboardEventInit));
el.value = keyChar;
el.dispatchEvent(new KeyboardEvent("keyup", keyboardEventInit));
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
} else {
console.log("el is null");
}
}
The following code can only work on ordinary websites, but it is invalid for strong website.
function fireKeyEvent(el, evtType, keyChar) {
el.addEventListener(evtType, function(e) {el.value += e.key;}, false);
el.focus();
const keyboardEventInit = {bubbles:false, cancelable:false, composed:false, key:keyChar, code:'', location:0};
var evtObj = new KeyboardEvent(evtType, keyboardEventInit);
el.dispatchEvent(evtObj);
}
Hi I'm querying for a specific video by title - and at the moment I get mixed results.
my videos are all named with a consecutive number at the end ie ANDNOW2022_00112, ANDNOW2022_00113 etc
When I search /videos/?fields=uri,name&query=ANDNOW2022_00112 I get all of the videos returned
I've also tried the query_fields using
/me/videos?query_fields=title&sort=alphabetical&query=ANDNOW2022_00112
I just want the one I've searched for - or a no results returned.
At the moment I get all of the videos with AN2022 in the title/name. Now 'usually' the one I searched for is at the top of the list but not everytime.
Any tips appreciated.
Okay I'm not going mad :)
This is from Vimeo and is here for those with the same issue - basically to get t to work you need to understand that:
After speaking with our engineers, the current search capability are not "Exact" search.
When adding numbers or underscores the search is split into parts so "ANDNOW2022_00112" is transforming the query into the parts "andnow2022", "andnow", "2022", and "00112". So this is why your seeing these results. Our engineering team are in the process of improving the search capabilities and hope to provide a release in the near future.
Which means for now I'll have to rename my files.
Preface:
Vimeo does not currently offer an API endpoint for exact title search — but even if it did — it's possible to upload multiple videos and assign them identical titles. There's no way to use the API to positively identify a video by title — this is why every uploaded video is assigned a unique ID.
Solution:
Because the API returns data which includes an array of video objects, you can solve this problem in the same way you'd solve any similar problem in JavaScript where you have to find an element in an array: Array.prototype.find()
Here's how you can apply it to your problem:
Query the API using the parameters you described in your question.
You might also be interested in using the sort and direction parameters for greater control over a deterministic sort order.
Find the first item in the returned array of video objects that match your expected text exactly, and return it (or undefined if it doesn't exist)
Here's a code example with some static data from the API that was used to search for the video Mercedes Benz from the user egarage — note that I've omitted quite a few (irrelevant) fields from the response in order to keep the example small:
// Mocking fetch for this example:
function fetch (_requestInfo, _init) {
const staticJson = `{"total":2,"page":1,"per_page":25,"paging":{"next":null,"previous":null,"first":"/users/egarage/videos?query_fields=title&query=Mercedes%20Benz&sort=alphabetical&direction=asc&page=1","last":"/users/egarage/videos?query_fields=title&query=Mercedes%20Benz&sort=alphabetical&direction=asc&page=1"},"data":[{"uri":"/videos/61310450","name":"50th Anniversary of the Pagoda SL -- Mercedes-Benz Classic Vehicles","description":"Penned by designer Paul Bracq, the W113 SL had big shoes to fill: it had the incredible task of succeeding the original and instantly iconic 300 SL Gullwing. But you can't copy a legend, so Bracq designed one of his own. Straight lines replaced curves and a low-slung roof was replaced by a high top design that gave the car its nickname: the Pagoda.\\n\\nMUSIC: Developer Over Time","type":"video","link":"https://vimeo.com/61310450"},{"uri":"/videos/55837293","name":"Mercedes Benz","description":"To celebrate Mercedes Benz 125th birthday, the 2011 Pebble Beach Concours d’Elegance showcased the models that trace the lineage to Benz and Daimler —particularly Mercedes-Benz. This tribute chronicled early racing greats, coachbuilt classics, and preservation cars. Produced in association with DriveCulture.","type":"video","link":"https://vimeo.com/55837293"}]}`;
return Promise.resolve(new Response(staticJson));
}
async function fetchVideoByTitle (token, userId, videoTitle) {
const url = new URL(`https://api.vimeo.com/users/${userId}/videos`);
url.searchParams.set("query_fields", "title");
url.searchParams.set("query", videoTitle);
url.searchParams.set("sort", "alphabetical");
url.searchParams.set("direction", "asc");
const headers = new Headers([
["Authorization", `Bearer ${token}`],
]);
const response = await fetch(url.href, {headers});
const parsedJson = await response.json();
// Find the video that matches (if it exists):
const maybeFirstVideoObj = parsedJson.data.find(video => video.name === videoTitle);
return maybeFirstVideoObj;
}
async function main () {
const video = await fetchVideoByTitle(
"YOU_ACTUAL_TOKEN",
"egarage",
"Mercedes Benz",
);
console.log(video); // {name: "Mercedes Benz", link: "https://vimeo.com/55837293", ...}
}
main();
My apologies in advance for the long post.
I am quite new to AWS Rekognition and Lambda, but I took on a project to build a facial recognition system using AWS S3, Rekognition and Lambda. I managed to get a working solution using a few of the Rekognition API's that are provided in the AWS JavaScript SDK Documentation, but it only works when there is one face in the input image. I started playing around with images that has multiple faces, but it doesn't give the response I'm looking for. After doing research I narrowed my problem down to the following:
I need to be able to specify what faces I want to index in an image with multiple faces using the indexFaces API.
NOTE: I'm using JavaScript.
My logic for a single face in an image is that I use the SearchFacesByImage API and I first see if I have indexed the face of Person 1 in the past to 'allFaces'. If I have, then I don't need to index Person 1's face again to 'allFaces', but if I have not, then I need to do that first.
Up until this point, everything works fine when I'm using an image with a single face as input. (See code example down below)
Here comes the problem, when I have an image with multiple faces, including the face of Person 1, it will index all the faces in that image, including Person 1's face again, and add it to the 'allFaces' collection, but what I want to achieve is where the system picks up that Person 1 has been indexed in the past, so it should not index Person 1 again, instead index all the other people in the image.
That's how I came to refine my problem to be able to specify what faces I want to index in an image that contains multiple faces, because if I can achieve that, then I can say that Person 1 has been indexed, so continue with Person 2.
In the indexFaces API, you can specify the "MaxFaces" and "QualityFilter" parameters. I have looked at that, but I don't believe that holds the answer to my solution so I'm steering away from that, unless it 100% holds the answer to my solution.
I'm also not sure if there might be an issue with my logic, or if my logic is okay but my lack in JavaScript knowledge is what's holding me back.
Here is what I've done thus far for a single face in an image:
const AWS = require('aws-sdk');
const s3 = new AWS.S3({apiVersion: "2006-03-01"});
const rekognition = new AWS.Rekognition();
//-----------------------------Exports Function-----------------------
exports.handler = function(event, context) {
bucket = event.Records[0].s3.bucket.name;
key = event.Records[0].s3.object.key;
console.log(bucket);
console.log(key);
searchingFacesByImage(bucket, key);
};
//--------------------------------------------------------------------
// Search for a face in an input image
function searchingFacesByImage(bucket, key) {
let params = {
CollectionId: "allFaces",
FaceMatchThreshold: 95,
Image: {
S3Object: {
Bucket: bucket,
Name: key
}
},
MaxFaces: 5
};
const searchingFace = rekognition.searchFacesByImage(params, function(err, searchdata) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
// console.log(JSON.stringify(searchdata, null, '\t'));
// if data.FaceMatches > 0 : There that face in the image exists in the collection
if (searchdata.FaceMatches.length > 0) {
console.log("Face is a match");
// Continue
} else {
console.log("Face is not a match");
console.log("Start indexing face to 'allFaces'");
indexToAllFaces(bucket, key);
}
}
});
return searchingFace;
}
//--------------------------------------------------------------------
// If face is not a match in 'allFaces', index face to 'allFaces' collection
function indexToAllFaces(bucket, key) {
let params = {
CollectionId: "allFaces",
DetectionAttributes: ['ALL'],
Image: {
S3Object: {
Bucket: bucket,
Name: key
}
}
};
const indexFace = rekognition.indexFaces(params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
console.log("INDEXING TO 'allFaces'");
console.log(JSON.stringify(data, null, '\t'));
}
});
return indexFace;
}
//--------------------------------------------------------------------
Like I said, this works fine when using images with a single face, so that is why I'm hoping to add some logic to filter through the faces in an image with multiple faces and whoever's face has been indexed in the past, should not be indexed again.
Thanks in advance for any feedback.
You will need to use DetectFaces() to obtain a list of all faces detected in the image.
The, for each Face returned:
Use the BoundingBox to copy and crop the image, so it only shows the given face
Use SearchFacesByImage() to determine whether it is already in the Face Collection
If it is not in the Face Collection, use IndexImages() to add it to the Face Collection. It will add the single face to the collection.
From experience, it is also a good idea to associate an ExternalImageId with each image added. This can contain your own reference to the face and can be used in a database to store additional information about the Face (eg id, name, or which picture they came from). The ExternalImageId will be returned with cetain calls when the face is detected in images.
I can't seem to get hour12 time working in node.js, however in the browser (Chrome) it's working just fine.
Node.js in terminal
var date = new Date();
var d12 = date.toLocaleTimeString('en-US', {hour12:true});
var d24 = date.toLocaleTimeString('en-US', {hour12:false});
console.log(d12) // output 13:43:38
console.log(d24) // output 13:43:38
Both yeild the same result:
13:43:38
Update
Adding fiddle to prove it works in browser
Could someone point me to the docs that explain why, or tell me what I'm doing wrong?
It's not just you. I tried running the same chunk in Node.js and couldn't get a way to print it in 12 hour format easily.
After doing some Googling, it seems like Moment.js is a popular tool for manipulating and displaying time and days. If you need to manipulate a lot of time/dates, it may be worth checking out, Moment.js.
// with Moment
var moment = require('moment');
console.log(moment().format('hh:mm'));
Otherwise,
// just one of many ways to do it in Javascript
function hour12 (hour) {
var mod = hour % 12;
if (mod < 10) {
return '0'.concat(mod);
} else {
return mod;
}
}
console.log(new Date().toLocaleTimeString().replace(/[\d]+/, hour12(date.getHours())));
EDIT I answered this question late at night, and realized I sort of missed the mark on addressing the question.
Since Node.js is based off Chrome's v8 JavaScript engine, I started poking around in the source code. I can't see a place where it takes into account arguments passed to it.
Code is here, toLocaleTimeString is line 324. In comparison, I looked around Mozilla's SpiderMonkey engine and it at a glance, it seems to account for this.
You can use toLocaleDateString and toLocaleTimeString to format times and dates. The first parameter passed to these methods is a locale value, such as "en-us". The second parameter, where present, specifies formatting options, such as the long form for the weekday.
I've used Chrome and works well.
var date = new Date(Date.UTC(2016, 3, 7, 14, 30, 0));
var options = {
weekday: "long", year: "numeric", month: "short",
day: "numeric", hour: "2-digit", minute: "2-digit"
};
document.write(date.toLocaleTimeString("en-US", options));
https://msdn.microsoft.com/en-us/library/ff743760(v=vs.94).aspx