Here is the Java code equivalent of the given Python code:

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.openai.OpenAIHelper;
import com.openai.YoutubeTranscriptApiHelper;
import com.openai.html.HtmlHelper;

public class Main {

    private static final int MAX_LENGTH = (int) (4000 * 2.5);

    private static Map<String, String> dataStore = new HashMap<>();

    public static void main(String[] args) {
        handler('pipedream');
    }

    public static Map<String, Object> handler(String pd) {
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> event = (Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) pd.get('steps'))
                .get('trigger')).get('event');
        Map<String, Object> message = (Map<String, Object>) event.get('message');
        String telegramUserId = String.valueOf(message.get('from').get('id'));
        String msg = String.valueOf(message.get('text'));
        if (msg.startsWith('\token')) {
            saveToken(pd, telegramUserId, msg.substring(7).trim());
            response.put('status', 400);
            response.put('message', 'OpenAI API token registered!');
            return response;
        }
        String openaiApiKey = getToken(pd, telegramUserId);
        if (openaiApiKey == null || openaiApiKey.isEmpty()) {
            response.put('status', 400);
            response.put('message', 'Please register your OpenAI API key with \token [OPENAI_TOKEN].');
            return response;
        }
        String[] content = createContent(msg);
        String subject = content[0];
        String url = content[1];
        String html = content[2];
        html = html.replace('\n', '<br>');
        html = '<html><body>' + html + '</body></html>';
        response.put('subject', subject);
        response.put('text', subject);
        response.put('url', url);
        response.put('html', html);
        response.put('markdown', html2text(html));
        response.put('status', 200);
        response.put('message', 'Saved on your XBrain!');
        return response;
    }

    public static void saveToken(Map<String, Object> pd, String userId, String token) {
        System.out.println('Saving token for user ' + userId + ', token: ' + token);
        dataStore.put(userId, token);
    }

    public static String getToken(Map<String, Object> pd, String userId) {
        return dataStore.get(userId);
    }

    public static String[] createContent(String userMsg) {
        String[] content = new String[3];
        if (userMsg.startsWith('/')) {
            String[] split = userMsg.split(' ', 2);
            String command = split[0];
            String text = split[1];
            if (text.isEmpty()) {
                throw new IllegalArgumentException('Content is empty');
            }
            if (command.equals('/sum') || command.equals('/tldr') || command.equals('/ask')) {
                content = gpt(command, text);
            } else {
                if (!command.equals('/add')) {
                    text = command + ' ' + text;
                }
                content = add(text);
            }
        } else {
            content = add(userMsg);
        }
        return content;
    }

    public static String[] add(String content) {
        String[] result = new String[2];
        String type = getContentType(content);
        if (type.equals('youtube')) {
            result = addYoutubeUrl(content);
            result[0] = 'XBrian: ' + result[0];
        } else if (type.equals('webpage')) {
            result = addWebpageUrl(content);
        } else {
            String[] split = content.split('\n', 2);
            result[0] = split[0];
            result[1] = split[1];
        }
        return result;
    }

    public static String[] gpt(String command, String content) {
        String[] result = new String[2];
        String type = getContentType(content);
        String subject = content.split('\n')[0];
        if (type.equals('youtube')) {
            String url = content.replaceAll('(https?://\S+)', '');
            String prompt = content.replace(url, '');
            subject = 'XBrian: ' + subject;
            String transcript = YoutubeTranscriptApiHelper.getTranscript(url);
            content = prompt + ' ' + transcript;
        } else if (type.equals('webpage')) {
            String url = content.replaceAll('(https?://\S+)', '');
            String prompt = content.replace(url, '');
            String[] html = HtmlHelper.downloadHtml(url);
            subject = 'XBrian: ' + html[0];
            content = prompt + ' ' + html[1];
        }
        result[0] = subject;
        result[1] = getAssistant(content, command);
        return result;
    }

    public static String[] addWebpageUrl(String url) {
        String[] result = new String[2];
        String[] html = HtmlHelper.downloadHtml(url);
        result[0] = html[0];
        result[1] = html[1] + HtmlHelper.addHtmlHyperlink(url);
        return result;
    }

    public static String[] addYoutubeUrl(String url) {
        String[] result = new String[2];
        String subject = HtmlHelper.getPageTitle(url);
        String transcript = YoutubeTranscriptApiHelper.getTranscript(url);
        result[0] = subject;
        result[1] = HtmlHelper.addHtmlHyperlink(url) + transcript;
        return result;
    }

    public static String getContentType(String content) {
        if (content.contains('youtu.be') || content.contains('youtube.com')) {
            return 'youtube';
        } else if (Pattern.matches('^https?://.*', content)) {
            return 'webpage';
        } else {
            return 'text';
        }
    }

    public static String getAssistant(String text, String command, String openaiToken) {
        if (text.length() > MAX_LENGTH) {
            System.out.println('WARNING: Content is too long. Length: ' + text.length());
            text = text.substring(0, MAX_LENGTH);
        }
        String openaiApiKey = openaiToken;
        if (openaiApiKey == null || openaiApiKey.isEmpty()) {
            openaiApiKey = getOpenaiApiKey();
        }
        return OpenAIHelper.chat(text, command, openaiApiKey);
    }

    public static String html2text(String html) {
        Document document = Jsoup.parse(html);
        return document.body().text();
    }

    public static String getOpenaiApiKey() {
        return ''; // Replace with your OpenAI API key
    }
}

Please note that some classes and methods are assumed to exist based on the Python code, so you may need to provide their implementation or imports.


原文地址: https://www.cveoy.top/t/topic/plJp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录