File size: 3,948 Bytes
0d2e704
9e11cef
417cd16
9e11cef
 
a0b2f3c
21d09ab
4991a9b
a0b2f3c
21d09ab
 
 
 
 
 
 
 
33c1a1e
a0b2f3c
2036883
33c1a1e
21d09ab
417cd16
3d21a93
 
a6573bc
417cd16
a0b2f3c
fada29a
38d8108
 
 
 
 
 
 
 
 
78d5f9d
 
38d8108
 
78d5f9d
38d8108
 
 
 
 
 
21d09ab
 
 
 
 
 
 
 
5f4ddbe
 
21d09ab
4991a9b
21d09ab
38d8108
 
 
 
21d09ab
 
4991a9b
38d8108
21d09ab
 
 
 
 
38d8108
21d09ab
4991a9b
 
fada29a
21d09ab
0d2e704
21d09ab
0d2e704
 
 
 
 
 
 
417cd16
5f41257
e53547c
 
ec8aa17
4991a9b
21d09ab
fada29a
 
0111163
 
 
 
 
 
 
 
 
 
b3fb86f
 
c317c89
 
21d09ab
 
2acf559
 
a6573bc
fada29a
 
33c1a1e
 
 
5f4ddbe
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
import json
import os
import re
import requests

import gradio as gr
from bs4 import BeautifulSoup
from spiralfilm import FilmCore, FilmConfig

from logging import getLogger, DEBUG, StreamHandler

logger = getLogger()
logger.setLevel(DEBUG)
handler = StreamHandler()
handler.setLevel(DEBUG)
logger.addHandler(handler)


def greet(name):
    return "こんにちは " + name + "さん!! \n僕はパスカルくんだよ。よろしくね"


def extract_texts(input_str):
    pattern = r"msg='([^']*)'"
    matches = re.findall(pattern, input_str)
    return list(map(lambda x: ''.join(x.split('\\n')), matches))


async def summarize(input_text: str, input_url: str):
    config = FilmConfig(
        "gpt-4-32k",
        api_type="azure",
        azure_deployment_id="gpt-4-32k",
        azure_api_version="2023-05-15",
        timeout=60.0,  # これを入れないとtimeoutが頻繁に発生する
    )
    config.get_apikey()

    if input_text:
        _prompt = f"""
            以下の文章を要約してください。
            {input_text}
        """
        return await FilmCore(
            prompt=_prompt,
            system_prompt="あなたは優秀なライターです。",
            config=config
        ).run_async()
    if input_url:
        try:
            res = requests.get(input_url)
            soup = BeautifulSoup(res.text)
            url_content = soup.find('title').text + '\n' + soup.find('body').text
            _prompt = f"""
            以下の文章を要約してください。
            {url_content}
            """
        except Exception as e:
            logger.error(e)
            raise gr.Error("WEBページの取得に失敗しました。")

        return await FilmCore(
            prompt=_prompt,
            system_prompt="あなたは優秀なライターです。",
            config=config
        ).run_async()
    else:
        raise gr.Error("LLMの実行に失敗しました。")


def validate_input_form(input_text, input_url):
    input_value = input_text + input_url
    # Check if the text is not blank
    if len(input_value) < 1:
        raise gr.Error("テキストかURLを入力してください。")
    else:
        return


async def chat(input_text, input_url):
    validate_input_form(input_text, input_url)
    summary = await summarize(input_text, input_url)
    logger.info(f"summary: {summary}")
    endpoint = os.environ.get("TWINROOM_API_BASE")
    payload = {
        "content": summary
    }
    headers = {'API-Key': os.environ.get("TWINROOM_API_KEY")}
    json_payload = json.dumps(payload)
    response = requests.post(endpoint, headers=headers, data=json_payload)
    response_msgs = extract_texts(response.text)
    result = '\n'.join(response_msgs)
    if input_url:
        result += f'\n{input_url}'
    return result


with gr.Blocks() as iface:
    # UI
    gr.Markdown(
        """
        # パスカルくん
        ## 使い方
        テキスト、もしくはURLにパスカルくんに分析させたい記事の内容やURLを入力して「Chats」ボタンを押すと回答が出力されます。  
  
        ※テキスト、URLの両方に入力して実行した場合は、**URLが優先されます。**  
        ※テキスト、URLの両方が**空の場合は実行できません。** 必ずいずれかを入力してから実行してください。
        """
    )
    with gr.Row():
        with gr.Column():
            input_text = gr.Textbox(label="テキスト")
            input_url = gr.Textbox(label="URL")

            chat_btn = gr.Button("Chats")
        with gr.Column():
            output_text = gr.Textbox(label="回答")

    # Event handler
    chat_btn.click(fn=chat, inputs=[input_text, input_url], outputs=output_text)


if __name__ == "__main__":
    iface.launch(auth=(os.environ.get("GRADIO_USER_NAME"), os.environ.get("GRADIO_PASSWORD")), share=True, server_name="0.0.0.0")