mirror of
https://github.com/mendableai/firecrawl.git
synced 2024-11-16 11:42:24 +08:00
now using compiled go/C lib with koffi
This commit is contained in:
parent
48056ea1bd
commit
291d9e375b
|
@ -17,8 +17,15 @@ RUN pnpm install
|
||||||
RUN --mount=type=secret,id=SENTRY_AUTH_TOKEN \
|
RUN --mount=type=secret,id=SENTRY_AUTH_TOKEN \
|
||||||
bash -c 'export SENTRY_AUTH_TOKEN="$(cat /run/secrets/SENTRY_AUTH_TOKEN)"; if [ -z $SENTRY_AUTH_TOKEN ]; then pnpm run build:nosentry; else pnpm run build; fi'
|
bash -c 'export SENTRY_AUTH_TOKEN="$(cat /run/secrets/SENTRY_AUTH_TOKEN)"; if [ -z $SENTRY_AUTH_TOKEN ]; then pnpm run build:nosentry; else pnpm run build; fi'
|
||||||
|
|
||||||
# Install packages needed for deployment
|
# Install Go 1.19
|
||||||
|
FROM golang:1.19 AS go-base
|
||||||
|
COPY src/lib/go-html-to-md /app/src/lib/go-html-to-md
|
||||||
|
|
||||||
|
# Install Go dependencies and build
|
||||||
|
RUN cd /app/src/lib/go-html-to-md && \
|
||||||
|
go mod tidy && \
|
||||||
|
go build -o html-to-markdown.so -buildmode=c-shared html-to-markdown.go && \
|
||||||
|
chmod +x html-to-markdown.so
|
||||||
|
|
||||||
FROM base
|
FROM base
|
||||||
RUN apt-get update -qq && \
|
RUN apt-get update -qq && \
|
||||||
|
@ -26,8 +33,7 @@ RUN apt-get update -qq && \
|
||||||
rm -rf /var/lib/apt/lists /var/cache/apt/archives
|
rm -rf /var/lib/apt/lists /var/cache/apt/archives
|
||||||
COPY --from=prod-deps /app/node_modules /app/node_modules
|
COPY --from=prod-deps /app/node_modules /app/node_modules
|
||||||
COPY --from=build /app /app
|
COPY --from=build /app /app
|
||||||
|
COPY --from=go-base /app/src/lib/go-html-to-md/html-to-markdown.so /app/src/lib/go-html-to-md/html-to-markdown.so
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Start the server by default, this can be overwritten at runtime
|
# Start the server by default, this can be overwritten at runtime
|
||||||
|
|
|
@ -86,6 +86,7 @@
|
||||||
"joplin-turndown-plugin-gfm": "^1.0.12",
|
"joplin-turndown-plugin-gfm": "^1.0.12",
|
||||||
"json-schema-to-zod": "^2.3.0",
|
"json-schema-to-zod": "^2.3.0",
|
||||||
"keyword-extractor": "^0.0.28",
|
"keyword-extractor": "^0.0.28",
|
||||||
|
"koffi": "^2.9.0",
|
||||||
"langchain": "^0.2.8",
|
"langchain": "^0.2.8",
|
||||||
"languagedetect": "^2.0.0",
|
"languagedetect": "^2.0.0",
|
||||||
"logsnag": "^1.0.0",
|
"logsnag": "^1.0.0",
|
||||||
|
|
|
@ -122,6 +122,9 @@ importers:
|
||||||
keyword-extractor:
|
keyword-extractor:
|
||||||
specifier: ^0.0.28
|
specifier: ^0.0.28
|
||||||
version: 0.0.28
|
version: 0.0.28
|
||||||
|
koffi:
|
||||||
|
specifier: ^2.9.0
|
||||||
|
version: 2.9.0
|
||||||
langchain:
|
langchain:
|
||||||
specifier: ^0.2.8
|
specifier: ^0.2.8
|
||||||
version: 0.2.8(@supabase/supabase-js@2.44.2)(axios@1.7.2)(cheerio@1.0.0-rc.12)(handlebars@4.7.8)(html-to-text@9.0.5)(ioredis@5.4.1)(mammoth@1.7.2)(mongodb@6.6.2(socks@2.8.3))(openai@4.57.0(zod@3.23.8))(pdf-parse@1.1.1)(puppeteer@22.12.1(typescript@5.4.5))(redis@4.6.14)(ws@8.18.0)
|
version: 0.2.8(@supabase/supabase-js@2.44.2)(axios@1.7.2)(cheerio@1.0.0-rc.12)(handlebars@4.7.8)(html-to-text@9.0.5)(ioredis@5.4.1)(mammoth@1.7.2)(mongodb@6.6.2(socks@2.8.3))(openai@4.57.0(zod@3.23.8))(pdf-parse@1.1.1)(puppeteer@22.12.1(typescript@5.4.5))(redis@4.6.14)(ws@8.18.0)
|
||||||
|
@ -3170,6 +3173,9 @@ packages:
|
||||||
resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==}
|
resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==}
|
||||||
engines: {node: '>=6'}
|
engines: {node: '>=6'}
|
||||||
|
|
||||||
|
koffi@2.9.0:
|
||||||
|
resolution: {integrity: sha512-KCsuJ2gM58n6bNdR2Z7gqsh/3TchxxQFbVgax2/UvAjRTgwNSYAJDx9E3jrkBP4jEDHWRCfE47Y2OG+/fiSvEw==}
|
||||||
|
|
||||||
langchain@0.2.8:
|
langchain@0.2.8:
|
||||||
resolution: {integrity: sha512-kb2IOMA71xH8e6EXFg0l4S+QSMC/c796pj1+7mPBkR91HHwoyHZhFRrBaZv4tV+Td+Ba91J2uEDBmySklZLpNQ==}
|
resolution: {integrity: sha512-kb2IOMA71xH8e6EXFg0l4S+QSMC/c796pj1+7mPBkR91HHwoyHZhFRrBaZv4tV+Td+Ba91J2uEDBmySklZLpNQ==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
@ -8492,6 +8498,8 @@ snapshots:
|
||||||
|
|
||||||
kleur@3.0.3: {}
|
kleur@3.0.3: {}
|
||||||
|
|
||||||
|
koffi@2.9.0: {}
|
||||||
|
|
||||||
langchain@0.2.8(@supabase/supabase-js@2.44.2)(axios@1.7.2)(cheerio@1.0.0-rc.12)(handlebars@4.7.8)(html-to-text@9.0.5)(ioredis@5.4.1)(mammoth@1.7.2)(mongodb@6.6.2(socks@2.8.3))(openai@4.57.0(zod@3.23.8))(pdf-parse@1.1.1)(puppeteer@22.12.1(typescript@5.4.5))(redis@4.6.14)(ws@8.18.0):
|
langchain@0.2.8(@supabase/supabase-js@2.44.2)(axios@1.7.2)(cheerio@1.0.0-rc.12)(handlebars@4.7.8)(html-to-text@9.0.5)(ioredis@5.4.1)(mammoth@1.7.2)(mongodb@6.6.2(socks@2.8.3))(openai@4.57.0(zod@3.23.8))(pdf-parse@1.1.1)(puppeteer@22.12.1(typescript@5.4.5))(redis@4.6.14)(ws@8.18.0):
|
||||||
dependencies:
|
dependencies:
|
||||||
'@langchain/core': 0.2.12(langchain@0.2.8(@supabase/supabase-js@2.44.2)(axios@1.7.2)(cheerio@1.0.0-rc.12)(handlebars@4.7.8)(html-to-text@9.0.5)(ioredis@5.4.1)(mammoth@1.7.2)(mongodb@6.6.2(socks@2.8.3))(openai@4.57.0(zod@3.23.8))(pdf-parse@1.1.1)(puppeteer@22.12.1(typescript@5.4.5))(redis@4.6.14)(ws@8.18.0))(openai@4.57.0(zod@3.23.8))
|
'@langchain/core': 0.2.12(langchain@0.2.8(@supabase/supabase-js@2.44.2)(axios@1.7.2)(cheerio@1.0.0-rc.12)(handlebars@4.7.8)(html-to-text@9.0.5)(ioredis@5.4.1)(mammoth@1.7.2)(mongodb@6.6.2(socks@2.8.3))(openai@4.57.0(zod@3.23.8))(pdf-parse@1.1.1)(puppeteer@22.12.1(typescript@5.4.5))(redis@4.6.14)(ws@8.18.0))(openai@4.57.0(zod@3.23.8))
|
||||||
|
|
7
apps/api/src/lib/go-html-to-md/README.md
Normal file
7
apps/api/src/lib/go-html-to-md/README.md
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
To build the go-html-to-md library, run the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd apps/api/src/lib/go-html-to-md
|
||||||
|
go build -o html-to-markdown.so -buildmode=c-shared html-to-markdown.go
|
||||||
|
chmod +x html-to-markdown.so
|
||||||
|
```
|
|
@ -1,11 +1,14 @@
|
||||||
module html-to-markdown.go
|
module html-to-markdown.go
|
||||||
|
|
||||||
go 1.22.6
|
go 1.19
|
||||||
|
|
||||||
require github.com/JohannesKaufmann/html-to-markdown v1.6.0
|
require github.com/JohannesKaufmann/html-to-markdown v1.6.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/PuerkitoBio/goquery v1.9.2 // indirect
|
github.com/PuerkitoBio/goquery v1.9.2 // indirect
|
||||||
github.com/andybalholm/cascadia v1.3.2 // indirect
|
github.com/andybalholm/cascadia v1.3.2 // indirect
|
||||||
|
github.com/kr/pretty v0.3.0 // indirect
|
||||||
golang.org/x/net v0.25.0 // indirect
|
golang.org/x/net v0.25.0 // indirect
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
)
|
)
|
||||||
|
|
|
@ -4,14 +4,22 @@ github.com/PuerkitoBio/goquery v1.9.2 h1:4/wZksC3KgkQw7SQgkKotmKljk0M6V8TUvA8Wb4
|
||||||
github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk=
|
github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk=
|
||||||
github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
|
github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
|
||||||
github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
|
github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
|
||||||
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
|
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||||
|
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||||
|
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
|
||||||
|
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
|
||||||
github.com/sebdah/goldie/v2 v2.5.3 h1:9ES/mNN+HNUbNWpVAlrzuZ7jE+Nrczbj8uFRjM7624Y=
|
github.com/sebdah/goldie/v2 v2.5.3 h1:9ES/mNN+HNUbNWpVAlrzuZ7jE+Nrczbj8uFRjM7624Y=
|
||||||
github.com/sebdah/goldie/v2 v2.5.3/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
|
github.com/sebdah/goldie/v2 v2.5.3/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
|
||||||
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
|
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
|
||||||
|
@ -75,7 +83,11 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
|
||||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||||
|
|
|
@ -1,41 +1,25 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"flag"
|
"C"
|
||||||
"fmt"
|
|
||||||
"log"
|
"log"
|
||||||
"sync"
|
|
||||||
|
|
||||||
md "github.com/JohannesKaufmann/html-to-markdown"
|
md "github.com/JohannesKaufmann/html-to-markdown"
|
||||||
"github.com/JohannesKaufmann/html-to-markdown/plugin"
|
"github.com/JohannesKaufmann/html-to-markdown/plugin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func convertHTMLToMarkdown(html string, wg *sync.WaitGroup, results chan<- string) {
|
//export ConvertHTMLToMarkdown
|
||||||
defer wg.Done()
|
func ConvertHTMLToMarkdown(html *C.char) *C.char {
|
||||||
converter := md.NewConverter("", true, nil)
|
converter := md.NewConverter("", true, nil)
|
||||||
converter.Use(plugin.GitHubFlavored())
|
converter.Use(plugin.GitHubFlavored())
|
||||||
|
|
||||||
markdown, err := converter.ConvertString(html)
|
markdown, err := converter.ConvertString(C.GoString(html))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
results <- markdown
|
return C.CString(markdown)
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
html := flag.String("html", "", "")
|
// This function is required for the main package
|
||||||
flag.Parse()
|
|
||||||
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
results := make(chan string, 1)
|
|
||||||
|
|
||||||
wg.Add(1)
|
|
||||||
go convertHTMLToMarkdown(*html, &wg, results)
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
close(results)
|
|
||||||
|
|
||||||
for markdown := range results {
|
|
||||||
fmt.Println(markdown)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,108 +1,106 @@
|
||||||
|
|
||||||
import { spawn } from 'node:child_process';
|
import koffi from 'koffi';
|
||||||
import { join } from 'node:path';
|
import { join } from 'path';
|
||||||
|
import "../services/sentry"
|
||||||
|
import * as Sentry from "@sentry/node";
|
||||||
|
|
||||||
|
import dotenv from 'dotenv';
|
||||||
|
import { Logger } from './logger';
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
export async function parseMarkdown(html: string): Promise<string> {
|
export async function parseMarkdown(html: string): Promise<string> {
|
||||||
if (!html) {
|
if (!html) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.env.USE_GO_MARKDOWN_PARSER == "true") {
|
try {
|
||||||
const goScriptPath = join(__dirname, 'go-html-to-md/html-to-markdown.go');
|
if (process.env.USE_GO_MARKDOWN_PARSER == "true") {
|
||||||
const goModDir = join(__dirname, 'go-html-to-md');
|
const goExecutablePath = join(__dirname, 'go-html-to-md/html-to-markdown.so');
|
||||||
const child = spawn('go', ['run', goScriptPath, '--html', html], {
|
const lib = koffi.load(goExecutablePath);
|
||||||
cwd: goModDir,
|
|
||||||
});
|
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
const convert = lib.func('Convert', 'string', ['string']);
|
||||||
let data = '';
|
|
||||||
|
|
||||||
child.stdout.on('data', (chunk) => {
|
let markdownContent = await new Promise<string>((resolve, reject) => {
|
||||||
data += chunk.toString(); // Convert Buffer to string
|
convert.async(html, (err: Error, res: string) => {
|
||||||
|
if (err) {
|
||||||
|
reject(err);
|
||||||
|
} else {
|
||||||
|
resolve(res);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
child.stderr.on('data', (chunk) => {
|
markdownContent = processMultiLineLinks(markdownContent);
|
||||||
reject(chunk.toString()); // Convert Buffer to string before rejecting
|
markdownContent = removeSkipToContentLinks(markdownContent);
|
||||||
});
|
return markdownContent;
|
||||||
|
|
||||||
child.on('close', (code) => {
|
|
||||||
if (code === 0) {
|
|
||||||
resolve(data.trim());
|
|
||||||
} else {
|
|
||||||
reject(new Error(`Process exited with code ${code}`));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
var TurndownService = require("turndown");
|
|
||||||
var turndownPluginGfm = require('joplin-turndown-plugin-gfm')
|
|
||||||
|
|
||||||
const turndownService = new TurndownService();
|
|
||||||
turndownService.addRule("inlineLink", {
|
|
||||||
filter: function (node, options) {
|
|
||||||
return (
|
|
||||||
options.linkStyle === "inlined" &&
|
|
||||||
node.nodeName === "A" &&
|
|
||||||
node.getAttribute("href")
|
|
||||||
);
|
|
||||||
},
|
|
||||||
replacement: function (content, node) {
|
|
||||||
var href = node.getAttribute("href").trim();
|
|
||||||
var title = node.title ? ' "' + node.title + '"' : "";
|
|
||||||
return "[" + content.trim() + "](" + href + title + ")\n";
|
|
||||||
},
|
|
||||||
});
|
|
||||||
var gfm = turndownPluginGfm.gfm;
|
|
||||||
turndownService.use(gfm);
|
|
||||||
let markdownContent = "";
|
|
||||||
const turndownPromise = new Promise<string>((resolve, reject) => {
|
|
||||||
try {
|
|
||||||
const result = turndownService.turndown(html);
|
|
||||||
resolve(result);
|
|
||||||
} catch (error) {
|
|
||||||
reject("Error converting HTML to Markdown: " + error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const timeoutPromise = new Promise<string>((resolve, reject) => {
|
|
||||||
const timeout = 5000; // Timeout in milliseconds
|
|
||||||
setTimeout(() => reject("Conversion timed out after " + timeout + "ms"), timeout);
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
markdownContent = await Promise.race([turndownPromise, timeoutPromise]);
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
return ""; // Optionally return an empty string or handle the error as needed
|
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
Sentry.captureException(error);
|
||||||
|
Logger.error(`Error converting HTML to Markdown with Go parser: ${error}`);
|
||||||
|
}
|
||||||
|
|
||||||
// multiple line links
|
// Fallback to TurndownService if Go parser fails or is not enabled
|
||||||
let insideLinkContent = false;
|
var TurndownService = require("turndown");
|
||||||
let newMarkdownContent = "";
|
var turndownPluginGfm = require('joplin-turndown-plugin-gfm');
|
||||||
let linkOpenCount = 0;
|
|
||||||
for (let i = 0; i < markdownContent.length; i++) {
|
|
||||||
const char = markdownContent[i];
|
|
||||||
|
|
||||||
if (char == "[") {
|
const turndownService = new TurndownService();
|
||||||
linkOpenCount++;
|
turndownService.addRule("inlineLink", {
|
||||||
} else if (char == "]") {
|
filter: function (node, options) {
|
||||||
linkOpenCount = Math.max(0, linkOpenCount - 1);
|
return (
|
||||||
}
|
options.linkStyle === "inlined" &&
|
||||||
insideLinkContent = linkOpenCount > 0;
|
node.nodeName === "A" &&
|
||||||
|
node.getAttribute("href")
|
||||||
|
);
|
||||||
|
},
|
||||||
|
replacement: function (content, node) {
|
||||||
|
var href = node.getAttribute("href").trim();
|
||||||
|
var title = node.title ? ' "' + node.title + '"' : "";
|
||||||
|
return "[" + content.trim() + "](" + href + title + ")\n";
|
||||||
|
},
|
||||||
|
});
|
||||||
|
var gfm = turndownPluginGfm.gfm;
|
||||||
|
turndownService.use(gfm);
|
||||||
|
|
||||||
if (insideLinkContent && char == "\n") {
|
try {
|
||||||
newMarkdownContent += "\\" + "\n";
|
let markdownContent = await turndownService.turndown(html);
|
||||||
} else {
|
markdownContent = processMultiLineLinks(markdownContent);
|
||||||
newMarkdownContent += char;
|
markdownContent = removeSkipToContentLinks(markdownContent);
|
||||||
}
|
|
||||||
}
|
|
||||||
markdownContent = newMarkdownContent;
|
|
||||||
|
|
||||||
// Remove [Skip to Content](#page) and [Skip to content](#skip)
|
|
||||||
markdownContent = markdownContent.replace(
|
|
||||||
/\[Skip to Content\]\(#[^\)]*\)/gi,
|
|
||||||
""
|
|
||||||
);
|
|
||||||
return markdownContent;
|
return markdownContent;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error converting HTML to Markdown: ", error);
|
||||||
|
return ""; // Optionally return an empty string or handle the error as needed
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function processMultiLineLinks(markdownContent: string): string {
|
||||||
|
let insideLinkContent = false;
|
||||||
|
let newMarkdownContent = "";
|
||||||
|
let linkOpenCount = 0;
|
||||||
|
for (let i = 0; i < markdownContent.length; i++) {
|
||||||
|
const char = markdownContent[i];
|
||||||
|
|
||||||
|
if (char == "[") {
|
||||||
|
linkOpenCount++;
|
||||||
|
} else if (char == "]") {
|
||||||
|
linkOpenCount = Math.max(0, linkOpenCount - 1);
|
||||||
|
}
|
||||||
|
insideLinkContent = linkOpenCount > 0;
|
||||||
|
|
||||||
|
if (insideLinkContent && char == "\n") {
|
||||||
|
newMarkdownContent += "\\" + "\n";
|
||||||
|
} else {
|
||||||
|
newMarkdownContent += char;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return newMarkdownContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeSkipToContentLinks(markdownContent: string): string {
|
||||||
|
// Remove [Skip to Content](#page) and [Skip to content](#skip)
|
||||||
|
const newMarkdownContent = markdownContent.replace(
|
||||||
|
/\[Skip to Content\]\(#[^\)]*\)/gi,
|
||||||
|
""
|
||||||
|
);
|
||||||
|
return newMarkdownContent;
|
||||||
|
}
|
|
@ -31,6 +31,7 @@ describe("Scraping Checkup (E2E)", () => {
|
||||||
|
|
||||||
describe("Scraping website tests with a dataset", () => {
|
describe("Scraping website tests with a dataset", () => {
|
||||||
it("Should scrape the website and prompt it against OpenAI", async () => {
|
it("Should scrape the website and prompt it against OpenAI", async () => {
|
||||||
|
let totalTimeTaken = 0;
|
||||||
let passedTests = 0;
|
let passedTests = 0;
|
||||||
const batchSize = 15; // Adjusted to comply with the rate limit of 15 per minute
|
const batchSize = 15; // Adjusted to comply with the rate limit of 15 per minute
|
||||||
const batchPromises = [];
|
const batchPromises = [];
|
||||||
|
@ -51,11 +52,16 @@ describe("Scraping Checkup (E2E)", () => {
|
||||||
const batchPromise = Promise.all(
|
const batchPromise = Promise.all(
|
||||||
batch.map(async (websiteData: WebsiteData) => {
|
batch.map(async (websiteData: WebsiteData) => {
|
||||||
try {
|
try {
|
||||||
|
const startTime = new Date().getTime();
|
||||||
const scrapedContent = await request(TEST_URL || "")
|
const scrapedContent = await request(TEST_URL || "")
|
||||||
.post("/v0/scrape")
|
.post("/v1/scrape")
|
||||||
.set("Content-Type", "application/json")
|
.set("Content-Type", "application/json")
|
||||||
.set("Authorization", `Bearer ${process.env.TEST_API_KEY}`)
|
.set("Authorization", `Bearer ${process.env.TEST_API_KEY}`)
|
||||||
.send({ url: websiteData.website, pageOptions: { onlyMainContent: true } });
|
.send({ url: websiteData.website });
|
||||||
|
|
||||||
|
const endTime = new Date().getTime();
|
||||||
|
const timeTaken = endTime - startTime;
|
||||||
|
totalTimeTaken += timeTaken;
|
||||||
|
|
||||||
if (scrapedContent.statusCode !== 200) {
|
if (scrapedContent.statusCode !== 200) {
|
||||||
console.error(`Failed to scrape ${websiteData.website} ${scrapedContent.statusCode}`);
|
console.error(`Failed to scrape ${websiteData.website} ${scrapedContent.statusCode}`);
|
||||||
|
@ -165,6 +171,7 @@ describe("Scraping Checkup (E2E)", () => {
|
||||||
const timeTaken = (endTime - startTime) / 1000;
|
const timeTaken = (endTime - startTime) / 1000;
|
||||||
console.log(`Score: ${score}%`);
|
console.log(`Score: ${score}%`);
|
||||||
console.log(`Total tokens: ${totalTokens}`);
|
console.log(`Total tokens: ${totalTokens}`);
|
||||||
|
console.log(`Total time taken: ${totalTimeTaken} miliseconds`);
|
||||||
|
|
||||||
await logErrors(errorLog, timeTaken, totalTokens, score, websitesData.length);
|
await logErrors(errorLog, timeTaken, totalTokens, score, websitesData.length);
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user