javaeeduke commited on
Commit
a871777
·
verified ·
1 Parent(s): 3cbf058

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -131
app.py CHANGED
@@ -1,138 +1,54 @@
1
  import os
2
- import requests
3
  import gradio as gr
4
- from huggingface_hub import InferenceClient
5
-
6
- # =====================
7
- # 配置 (从环境变量安全读取)
8
- # =====================
9
- # 获取 Hugging Face 的 Access Token(在后台 Settings -> Secrets 里配置)
10
- HF_TOKEN = os.getenv("HF_TOKEN")
11
- PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
12
-
13
- # 初始化 Hugging Face 免费大模型客户端
14
- # 使用官方推荐且对中文支持极好的 Qwen 2.5 7B 模型,完全运行在 HF 云端,不吃本地内存
15
- client = InferenceClient("Qwen/Qwen-2.5-7B-Instruct", token=HF_TOKEN)
16
-
17
- # =====================
18
- # AI文章生成(HF 免费版)
19
- # =====================
20
- def generate_article(keyword):
21
- prompt = f"""
22
- 请根据关键词《{keyword}》写一篇适合今日头条发布的文章。
23
-
24
- 要求:
25
- 1. 标题吸引人
26
- 2. 正文800字左右
27
- 3. 分段清晰
28
- 4. 结尾总结
29
- """
30
  try:
31
- # 使标准的 chat.completions 接口,完全免费
32
  response = client.chat.completions.create(
33
- model="Qwen/Qwen-2.5-7B-Instruct",
34
- messages=[
35
- {
36
- "role": "user",
37
- "content": prompt
38
- }
39
- ],
40
- temperature=0.8,
41
- max_tokens=1500
42
- )
43
- return response.choices[0].message.content
44
- except Exception as e:
45
- return f"文章生成失败,原因:{str(e)}\n\n💡 提示:如果提示无权限,请检查是否在 Space 的 Settings -> Secrets 中正确配置了 HF_TOKEN。"
46
-
47
- # =====================
48
- # 搜图 (Pexels API)
49
- # =====================
50
- def search_images(keyword):
51
- if not PEXELS_API_KEY:
52
- return []
53
-
54
- url = "https://api.pexels.com/v1/search"
55
- headers = {
56
- "Authorization": PEXELS_API_KEY
57
- }
58
- params = {
59
- "query": keyword,
60
- "per_page": 6
61
- }
62
-
63
- try:
64
- res = requests.get(
65
- url,
66
- headers=headers,
67
- params=params,
68
- timeout=20
69
  )
70
- data = res.json()
71
 
72
- images = []
73
- for photo in data.get("photos", []):
74
- images.append(photo["src"]["medium"])
75
- return images
76
- except:
77
- return []
78
-
79
- # =====================
80
- # 视频搜索(示例)
81
- # =====================
82
- def search_videos(keyword):
83
- # 用标准 Markdown 语法包装超链接
84
- links = [
85
- f"[在 YouTube 上搜索 《{keyword}》](https://www.youtube.com/results?search_query={keyword})"
86
- ]
 
 
 
 
 
 
87
 
88
- # 采用纯文本符号 !!! 代替复杂 emoji,防止系统字体缺失导致乱码
89
- result = "### !!! 相关视频搜索链接\n"
90
- result += "\n".join([f"- {link}" for link in links])
91
- return result
92
-
93
- # =====================
94
- # 主函数
95
- # =====================
96
- def main(keyword):
97
- if not keyword.strip():
98
- return "请输入有效的关键词!", [], "### !!! 请输入关键词"
99
-
100
- article = generate_article(keyword)
101
- images = search_images(keyword)
102
- videos = search_videos(keyword)
103
- return article, images, videos
104
-
105
- # =====================
106
- # Gradio界面布局(安全兼容版)
107
- # =====================
108
- with gr.Blocks(title="头条 AI Agent") as demo:
109
-
110
- gr.Markdown("# 头条 AI Agent (HF 免费版)")
111
- gr.Markdown("输入关键词,依托 Hugging Face 免费云端算力一键生成爆款文章、匹配图片和视频资源。")
112
-
113
- # 布局:上方输入栏
114
- with gr.Row():
115
- keyword_input = gr.Textbox(
116
- label="关键词",
117
- placeholder="例如:人工智能新趋势",
118
- scale=4
119
- )
120
- btn = gr.Button("立即生成", variant="primary", scale=1)
121
-
122
- # 布局:下方左右分栏
123
- with gr.Row():
124
- # 左栏:文章输出
125
- with gr.Column(scale=2):
126
- article_output = gr.Textbox(
127
- label="生成文章",
128
- lines=22
129
- )
130
-
131
- # 右栏:素材匹配
132
- with gr.Column(scale=1):
133
- gallery_output = gr.Gallery(
134
- label="匹配素材(Pexels 免费商用图)",
135
- columns=2,
136
- rows=3,
137
- height=350
138
- )
 
1
  import os
2
+ import gradio as block
3
  import gradio as gr
4
+ from openai import OpenAI
5
+
6
+ # 1. 从环境变量读取 FreeLLMAPI 的配置
7
+ FREE_LLM_API_URL = os.getenv("FREE_LLM_API_URL", "https://你的FreeLLMAPI地址.hf.space/v1")
8
+ FREE_LLM_API_KEY = os.getenv("FREE_LLM_API_KEY", "your_api_key_here")
9
+
10
+ # 2. 初始化 OpenAI 客户端(桥接 FreeLLMAPI)
11
+ client = OpenAI(
12
+ base_url=FREE_LLM_API_URL,
13
+ api_key=FREE_LLM_API_KEY
14
+ )
15
+
16
+ def predict(message, history):
17
+ # 将 Gradio 的历史记录转换为 OpenAI 格式
18
+ history_openai = []
19
+ for human, ai in history:
20
+ history_openai.append({"role": "user", "content": human})
21
+ history_openai.append({"role": "assistant", "content": ai})
22
+ history_openai.append({"role": "user", "content": message})
23
+
 
 
 
 
 
 
24
  try:
25
+ # FreeLLMAPI 聚合的模型(例如 gemini)
26
  response = client.chat.completions.create(
27
+ model="gemini",
28
+ messages=history_openai,
29
+ stream=True # 开启流式传输,体验更好
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  )
 
31
 
32
+ partial_message = ""
33
+ for chunk in response:
34
+ if chunk.choices[0].delta.content:
35
+ partial_message = partial_message + chunk.choices[0].delta.content
36
+ yield partial_message
37
+
38
+ except Exception as e:
39
+ yield f"⚠️ 链接 FreeLLMAPI 出错: {str(e)}"
40
+
41
+ # 3. 极简的 Gradio 聊天界面
42
+ demo = gr.ChatInterface(
43
+ fn=predict,
44
+ title="AI 自动化助手 (Gradio + FreeLLMAPI)",
45
+ textbox=gr.Textbox(placeholder="请输入内容...", container=False, scale=7)
46
+ )
47
+
48
+ if __name__ == "__main__":
49
+ # 注意:在 Docker 环境下,server_name 必须是 "0.0.0.0"
50
+ # 这里我们直接读取 Dockerfile 里配置好的环境变量
51
+ server_name = os.getenv("GRADIO_SERVER_NAME", "0.0.0.0")
52
+ server_port = int(os.getenv("GRADIO_SERVER_PORT", 7860))
53
 
54
+ demo.queue().launch(server_name=server_name, server_port=server_port)