aboutsummaryrefslogtreecommitdiff
path: root/bridges/AnthropicBridge.php
blob: 1272d35f579ef9eef8aa8596097abf7054cffa74 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
<?php

class AnthropicBridge extends BridgeAbstract
{
    const MAINTAINER = 'sqrtminusone';
    const NAME = 'Anthropic Research Bridge';
    const URI = 'https://www.anthropic.com';

    const CACHE_TIMEOUT = 3600; // 1 hour
    const DESCRIPTION = 'Returns research publications from Anthropic';

    const PARAMETERS = [
        '' => [
            'limit' => [
                'name' => 'Limit',
                'type' => 'number',
                'required' => true,
                'defaultValue' => 10
            ],
        ]
    ];

    public function collectData()
    {
        // Anthropic sometimes returns 500 for no reason. The contents are still there.
        $html = $this->getHTMLIgnoreError(self::URI . '/research');
        $limit = $this->getInput('limit');

        $page_data = $this->extractPageData($html);
        $pages = $this->parsePageData($page_data);
        for ($i = 0; $i < min(count($pages), $limit); $i++) {
            $page = $pages[$i];
            $page['content'] = $this->parsePage($page['uri']);
            $this->items[] = $page;
        }
    }

    private function getHTMLIgnoreError($url, $ttl = null)
    {
        if ($ttl != null) {
            $cacheKey = 'pages_' . $url;
            $content = $this->cache->get($cacheKey);
            if ($content) {
                return str_get_html($content);
            }
        }

        try {
            $content = getContents($url);
        } catch (HttpException $e) {
            $content = $e->response->getBody();
        }
        if ($ttl != null) {
            $this->cache->set($cacheKey, $content, $ttl);
        }
        return str_get_html($content);
    }

    private function extractPageData($html)
    {
        foreach ($html->find('script') as $script) {
            $js_code = $script->innertext;
            if (!str_starts_with($js_code, 'self.__next_f.push(')) {
                continue;
            }
            $push_data = (string)json_decode(mb_substr($js_code, 22, mb_strlen($js_code) - 2 - 22));
            $square_bracket = mb_strpos($push_data, '[');
            $push_array = json_decode(mb_substr($push_data, $square_bracket), true);
            if ($push_array == null || count($push_array) < 4) {
                continue;
            }
            $page_data = $push_array[3];
            if ($page_data != null && array_key_exists('page', $page_data)) {
                return $page_data;
            }
        }
    }

    private function parsePageData($page_data)
    {
        $result = [];
        foreach ($page_data['page']['sections'] as $section) {
            if (
                !array_key_exists('internalName', $section) ||
                $section['internalName'] != 'Research Teams'
            ) {
                continue;
            }
            foreach ($section['tabPages'] as $tabPage) {
                if ($tabPage['label'] != 'Overview') {
                    continue;
                }
                foreach ($tabPage['sections'] as $section1) {
                    if (
                        !array_key_exists('title', $section1)
                        || $section1['title'] != 'Publications'
                    ) {
                        continue;
                    }
                    foreach ($section1['posts'] as $post) {
                        $enc = [];
                        if ($post['cta'] != null && array_key_exists('url', $post['cta'])) {
                            $enc = [$post['cta']['url']];
                        }
                        $result[] = [
                            'title' => $post['title'],
                            'timestamp' => $post['publishedOn'],
                            'uri' => self::URI . '/research/' . $post['slug']['current'],
                            'categories' => array_map(
                                fn($s) => $s['label'],
                                $post['subjects'],
                            ),
                            'enclosures' => $enc,
                        ];
                    }
                    break;
                }
                break;
            }
            break;
        }
        return $result;
    }

    private function parsePage($url)
    {
        // Again, 500 for no reason.
        $html = $this->getHTMLIgnoreError($url, 7 * 24 * 60 * 60);

        $content = '';

        // Main content
        $main = $html->find('div[class*="PostDetail_post-detail"] > article', 0);

        // Mostly YouTube videos
        $iframes = $main->find('iframe');
        foreach ($iframes as $iframe) {
            $iframe->parent->removeAttribute('style');
            $iframe->outertext = '<a href="' . $iframe->src . '">' . $iframe->src . '</a>';
        }

        $main = convertLazyLoading($main);
        $main = defaultLinkTo($main, self::URI);
        $content .= $main;
        return $content;
    }
}