File size: 1,794 Bytes
c679d00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
733afa2
c679d00
 
 
 
 
 
 
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
import asyncio
from gnews import GNews
import fastapi_poe as fp
import gradio as gr

# 初始化GNews
google_news = GNews(language='en', country='US')

api_key = 'Mz4yhxQiIySrGas7qGElXtnYgzJCyJDUltrpFcZpolI'  # 确保替换为你的API密钥

# 定义异步函数来生成每个新闻的博客文章
async def generate_blog_for_news(article, index):
    news_text = f"Title: {article['title']}\nDescription: {article['description']}\nURL: {article['url']}\n\nPlease write a blog post about this news."
    
    message = fp.ProtocolMessage(role="user", content=news_text)
    complete_text = ''
    
    async for partial in fp.get_bot_response(messages=[message], bot_name="Mixtral-8x7B-Chat", api_key=api_key):
        complete_text += partial.text

    file_path = f'Blog_Article_{index}.txt'
    with open(file_path, 'w') as file:
        file.write(complete_text)

    return file_path

# 运行异步函数为每条新闻生成博客文章,并收集文件路径
async def main():
    top_news = google_news.get_top_news()
    top_10_news = top_news[:1]  # 获取前2条新闻来生成博客

    file_paths = await asyncio.gather(*(generate_blog_for_news(article, index) for index, article in enumerate(top_10_news, 1)))
    return file_paths

# 将异步main函数包装为同步函数,以便Gradio使用
def run_main():
    return asyncio.run(main())

# Gradio界面函数,修改以返回文件路径
def create_blog():
    file_paths = run_main()
    return file_paths

# 设置Gradio界面
iface = gr.Interface(
    fn=create_blog,
    inputs=None,
    outputs=gr.File(label="Download Blog Posts"),
    title="自动博客生成器",
    description="点击按钮生成博客文章,并提供下载链接!"
)

# 运行Gradio app
if __name__ == "__main__":
    iface.launch()