Spaces:
Sleeping
Sleeping
import asyncio | |
from gnews import GNews | |
import fastapi_poe as fp | |
import gradio as gr | |
import os | |
# 初始化GNews | |
google_news = GNews(language='en', country='US') | |
api_key = os.getenv('API_KEY') # 确保替换为你的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() | |