Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add js sdk folder to fish-tank #75

Merged
merged 26 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
0c25cb0
Add js sdk folder to fish-tank
frankfeng98 Oct 28, 2024
7b4f43f
Update formatting
frankfeng98 Oct 28, 2024
9de8235
Add placeholder files
frankfeng98 Oct 28, 2024
66c82e3
Update naming of the file
frankfeng98 Oct 28, 2024
c9ea375
Add one more example
frankfeng98 Oct 29, 2024
8ee3b01
kate/tf 3913 application collect ecommerce pricing data (#81)
KateZhang98 Oct 29, 2024
380c262
Add js example for list query usage (#83)
thakkerurvish Oct 30, 2024
a03e11a
add save / load authenticated session js sdk example. ran script and…
lozzle Oct 30, 2024
4477e87
Add close-popup files (#76)
SuveenE-TF Oct 30, 2024
384a67a
Close cookie popup js sdk (#77)
aarontantf Oct 30, 2024
2b5f1b4
Add log-into-sites examples (#79)
SuveenE-TF Oct 30, 2024
2bb7af2
Compare Product Prices Example (#78)
jinyangTF Oct 31, 2024
f02afc4
Add headless browser script (#85)
Zechereh Oct 31, 2024
09399d2
Add Getting Started YT script (#90)
colriot Nov 1, 2024
010f559
Add wait for entire page to load example script
Zechereh Nov 1, 2024
2cdd115
Js stealth mode example (#80)
TinyGambe Nov 4, 2024
5f7527c
Add xpath application example (#92)
Zechereh Nov 4, 2024
1dc3197
Added javascript sentiment analysis script (#94)
Zechereh Nov 4, 2024
408ac66
Add wait for entire page to load example script (#95)
Zechereh Nov 4, 2024
ad248ac
submit form js example (#89)
joshkung247 Nov 5, 2024
7eb3413
Add get_by_prompt example
frankfeng98 Nov 5, 2024
ec4bdb6
Merge branch 'add_js_sdk_examples_folder' of github.com:tinyfish-io/f…
frankfeng98 Nov 5, 2024
085e4a7
Fix formatting
frankfeng98 Nov 5, 2024
1a7d682
add interact with existing browser example
frankfeng98 Nov 5, 2024
ce9ad3f
Update interact with existing browser example
frankfeng98 Nov 5, 2024
f024082
address comments & fix examples
frankfeng98 Nov 6, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion .github/workflows/precommit.yml
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please have 2 separate precommit flows and add filtering for the path. Otherwise both python and JS flows will run regardless of where the change was made. I.e. we don't want to run JS precommit if python code was changed

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Understood! I will update it in the upcoming PRs. For now, I will leave as it is so people could merge into this branch.

Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ on:
types: [opened, synchronize, reopened]

jobs:
pre-commit:
python-pre-commit:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we call this pre-commit if it's already a PR-time check?

name: Pre-commit checks
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -49,3 +49,27 @@ jobs:
continue-on-error: true
with:
pylance-version: latest-release

js-pre-commit:
name: JS Pre-commit checks
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4

- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: "20"

- name: Install dependencies
working-directory: ./javascript-sdk
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should just call the folder js. it's not SDK, and JS a pretty widespread short name

run: npm install

- name: Run ESLint
working-directory: ./javascript-sdk
run: npm run lint

- name: Run Prettier
working-directory: ./javascript-sdk
run: npx prettier --check .
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,5 @@ logs/
tmp/

*env.local

javascript-sdk/node_modules
6 changes: 4 additions & 2 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
"GitHub.copilot",
"esbenp.prettier-vscode",
"ms-python.isort",
"ms-python.pylint"
"ms-python.pylint",
"dbaeumer.vscode-eslint",
"yoavbls.pretty-ts-errors",
]
}
}
12 changes: 12 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features"
},
"[javascriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"eslint.workingDirectories": [
{
"directory": "./javascript-sdk",
"changeProcessCWD": true
}
],
"editor.formatOnSave": true,
"files.insertFinalNewline": true,
"black-formatter.args": [
Expand Down
14 changes: 14 additions & 0 deletions JS/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* eslint-env node */
module.exports = {
root: true,
env: {
browser: true,
es6: true,
node: true,
},
extends: ['eslint:recommended', 'prettier'],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
};
9 changes: 9 additions & 0 deletions JS/.prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = {
printWidth: 100,
trailingComma: 'all',
singleQuote: true,
importOrder: ['<THIRD_PARTY_MODULES>', '^@/types/(.*)$', '^@/lib/(.*)$', '^[./]'],
importOrderSeparation: true,
importOrderSortSpecifiers: true,
importOrderCaseInsensitive: false,
};
17 changes: 17 additions & 0 deletions JS/application-examples/collect-youtube-comments/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Example script: interacting with YouTube website and extracting video information using AgentQL

This is an example of interacting with YouTube website and extracting video information using AgentQL.

## Run the script

- [Install AgentQL SDK](https://docs.agentql.com/javascript-sdk/installation)
- Save this JavaScript file locally as **main.js**
- Run the following command from the project's folder:

```bash
node main.js
```

## Play with the query

Install the [AgentQL Debugger Chrome extension](https://docs.agentql.com/installation/chrome-extension-installation) to play with the AgentQL query. [Learn more about the AgentQL query language](https://docs.agentql.com/agentql-query/query-intro)
96 changes: 96 additions & 0 deletions JS/application-examples/collect-youtube-comments/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const { chromium } = require('playwright');
const { configure, wrap } = require('agentql');

const URL = 'https://www.youtube.com/';

async function main() {
// Configure the AgentQL API key
configure({
apiKey: process.env.AGENTQL_API_KEY, // This is the default and can be omitted.
});

const browser = await chromium.launch({ headless: false });
const page = await wrap(await browser.newPage());
await page.goto(URL);

const SEARCH_QUERY = `
{
search_input
search_btn
}
`;

const VIDEO_QUERY = `
{
videos[] {
video_link
video_title
channel_name
}
}
`;

const VIDEO_CONTROL_QUERY = `
{
play_or_pause_btn
expand_description_btn
}
`;

const DESCRIPTION_QUERY = `
{
description_text
}
`;

const COMMENT_QUERY = `
{
comments[] {
channel_name
comment_text
}
}
`;

try {
// search query
const searchResponse = await page.queryElements(SEARCH_QUERY);
await searchResponse.search_input.type('machine learning', { delay: 75 });
await searchResponse.search_btn.click();

// video query
const videoResponse = await page.queryElements(VIDEO_QUERY);
console.log(
`Clicking Youtube Video: ${await videoResponse.videos[0].video_title.textContent()}`,
);
await videoResponse.videos[0].video_link.click(); // click the first youtube video

// video control query
const controlResponse = await page.queryElements(VIDEO_CONTROL_QUERY);
await controlResponse.expand_description_btn.click();

// description query
const descriptionData = await page.queryData(DESCRIPTION_QUERY);
console.log(`Captured the following description:\n${descriptionData.description_text}`);

// Scroll down the page to load more comments
for (let i = 0; i < 3; i++) {
await page.keyboard.press('PageDown');
await page.waitForLoadState();
}

// comment query
const commentResponse = await page.queryData(COMMENT_QUERY);
console.log(`Captured ${commentResponse.comments?.length || 0} comments!`);
} catch (error) {
console.error(`Found Error: ${error}`);
throw error;
}

// Used only for demo purposes. It allows you to see the effect of the script.
await page.waitForTimeout(10000);

await browser.close();
}

main();
29 changes: 29 additions & 0 deletions JS/application-examples/perform-sentiment-analysis/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Example script: perform sentiment analysis with AgentQL

This example demonstrates how to perform sentiment analysis on YouTube comments with AgentQL and OpenAI's GPT-3.5 model.

## Run the script

- [Install AgentQL SDK](https://docs.agentql.com/javascript-sdk/installation)
- [Install OpenAI SDK](https://www.npmjs.com/package/openai) with the following command:

```bash
npm install openai
```

- Save this JavaScript file locally as **main.js**
- Set your OpenAI API key as an environment variable with the following command:

```bash
export OPENAI_API_KEY="My API Key"
```

- Run the following command from the project's folder:

```bash
node main.js
```

## Play with the query

Install the [AgentQL Debugger Chrome extension](https://docs.agentql.com/installation/chrome-extension-installation) to play with the AgentQL query. [Learn more about the AgentQL query language](https://docs.agentql.com/agentql-query/query-intro)
99 changes: 99 additions & 0 deletions JS/application-examples/perform-sentiment-analysis/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/* This example demonstrates how to perform sentiment analysis on YouTube comments with AgentQL and OpenAI's GPT-3.5 model. */

const { wrap, configure } = require('agentql');
const { chromium } = require('playwright');

// Import the OpenAI API client.
const { OpenAI } = require('openai/index.mjs');

// Define the URL of the page to scrape.
const URL = 'https://www.youtube.com/watch?v=JfM1mr2bCuk';

// Define a query to interact with the page.
const QUERY = `
{
video_title
video_channel
comments[] {
comment_text
author
}
}
`;

async function getComments() {
// Configure the AgentQL API key
configure({
apiKey: process.env.AGENTQL_API_KEY, // This is the default and can be omitted.
});

// Launch a headless browser using Playwright.
const browser = await chromium.launch({ headless: false });

// Create a new page in the browser and wrap it to get access to the AgentQL's querying API
const page = await wrap(await browser.newPage());
await page.goto(URL);

for (let i = 0; i < 5; i++) {
// Scroll down the page to load more comments.
await page.waitForPageReadyState();

// Scroll down the page to load more comments
await page.keyboard.press('PageDown');
}

// Use queryData() method to fetch the video information from the page.
const response = await page.queryData(QUERY);

// Close the browser
await browser.close();

return response;
}

async function performSentimentAnalysis(comments) {
// User message construction
let USER_MESSAGE =
'These are the comments on the video. I am trying to understand the sentiment of the comments.';

// Append each comment's text to USER_MESSAGE
comments.comments.forEach((comment) => {
USER_MESSAGE += comment.comment_text;
});

// Define the system message
const SYSTEM_MESSAGE = `You are an expert in understanding social media analytics and specialize in analyzing the sentiment of comments.
Please find the comments on the video as follows:
`;

// Append request for a summary and takeaways
USER_MESSAGE +=
' Could you please provide a summary of the comments on the video. Additionally, just give only 3 takeaways which would be important for me as the creator of the video.';

// Initialize OpenAI client
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

try {
const response = await client.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [
{ role: 'system', content: SYSTEM_MESSAGE },
{ role: 'user', content: USER_MESSAGE },
],
});

// Return the content of the first completion choice
return response.choices[0].message.content;
} catch (error) {
console.error('Error during API call:', error);
throw error;
}
}

async function main() {
const comments = await getComments();
const summary = await performSentimentAnalysis(comments);
console.log(summary);
}

main();
26 changes: 26 additions & 0 deletions JS/application-examples/submit-form/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Example script: Automating form submission using AgentQL

This is an example of automating form submission on a website using AgentQL.

## Run the script

- [Install AgentQL SDK](https://docs.agentql.com/javascript-sdk/installation)
- Save this JavaScript file locally as **main.js**
- Run the following command from the project's folder:

```bash
node main.js
```

## Code explanation

This script demonstrates how to:

1. Navigate to a form page
2. Fill out form fields using AgentQL queries
3. Submit the form and handle the confirmation
4. Wait for the submission to complete

## Play with the query

Install the [AgentQL Debugger Chrome extension](https://docs.agentql.com/installation/chrome-extension-installation) to play with the AgentQL query. [Learn more about the AgentQL query language](https://docs.agentql.com/agentql-query/query-intro)
Loading
Loading