juanmaguitar commited on
Commit
c2fb256
·
1 Parent(s): cfebff8

wordpress_media tool

Browse files
Files changed (2) hide show
  1. app.py +9 -2
  2. tools/wordpress_media.py +103 -0
app.py CHANGED
@@ -11,6 +11,7 @@ from tools.blog_generator import BlogGeneratorTool
11
  from tools.visit_webpage import VisitWebpageTool
12
  from tools.web_search import DuckDuckGoSearchTool
13
  from tools.html_to_wp_blocks import HTMLToWPBlocksTool
 
14
 
15
  from Gradio_UI import GradioUI
16
 
@@ -156,6 +157,7 @@ with open("prompts.yaml", 'r') as stream:
156
 
157
  # Initialize WordPress tools
158
  wordpress_post = WordPressPostTool(wordpress_credentials)
 
159
  blog_generator = BlogGeneratorTool(model=model)
160
  html_to_blocks = HTMLToWPBlocksTool()
161
 
@@ -168,6 +170,7 @@ agent = CodeAgent(
168
  quick_research,
169
  # get_weather,
170
  wordpress_post,
 
171
  blog_generator,
172
  html_to_blocks,
173
  visit_webpage,
@@ -187,6 +190,7 @@ prompt_templates["system_prompt"] += """
187
 
188
  You are also capable of managing a WordPress blog through the following tools:
189
  - wordpress_post: Publishes posts to WordPress
 
190
  - blog_generator: Generates AI-written blog posts
191
  - html_to_blocks: Converts HTML content to WordPress Gutenberg blocks format
192
 
@@ -195,11 +199,14 @@ Always check credentials before attempting to post content.
195
  Example WordPress workflow:
196
  1. Set credentials (first time only)
197
  2. Generate blog content
198
- 3. Convert HTML content to WordPress blocks format
199
- 4. Publish blocks-formatted content to WordPress
 
 
200
 
201
  Remember to:
202
  - ALWAYS convert HTML content to WordPress blocks format before publishing
 
203
  - Validate WordPress credentials before posting
204
  - Generate high-quality, relevant content
205
  - Handle errors gracefully
 
11
  from tools.visit_webpage import VisitWebpageTool
12
  from tools.web_search import DuckDuckGoSearchTool
13
  from tools.html_to_wp_blocks import HTMLToWPBlocksTool
14
+ from tools.wordpress_media import WordPressMediaTool
15
 
16
  from Gradio_UI import GradioUI
17
 
 
157
 
158
  # Initialize WordPress tools
159
  wordpress_post = WordPressPostTool(wordpress_credentials)
160
+ wordpress_media = WordPressMediaTool(wordpress_credentials)
161
  blog_generator = BlogGeneratorTool(model=model)
162
  html_to_blocks = HTMLToWPBlocksTool()
163
 
 
170
  quick_research,
171
  # get_weather,
172
  wordpress_post,
173
+ wordpress_media,
174
  blog_generator,
175
  html_to_blocks,
176
  visit_webpage,
 
190
 
191
  You are also capable of managing a WordPress blog through the following tools:
192
  - wordpress_post: Publishes posts to WordPress
193
+ - wordpress_media: Uploads media files to WordPress and returns attachment URLs
194
  - blog_generator: Generates AI-written blog posts
195
  - html_to_blocks: Converts HTML content to WordPress Gutenberg blocks format
196
 
 
199
  Example WordPress workflow:
200
  1. Set credentials (first time only)
201
  2. Generate blog content
202
+ 3. Generate or prepare media files
203
+ 4. Upload media files to WordPress using wordpress_media tool
204
+ 5. Convert HTML content to WordPress blocks format, including media blocks
205
+ 6. Publish blocks-formatted content to WordPress
206
 
207
  Remember to:
208
  - ALWAYS convert HTML content to WordPress blocks format before publishing
209
+ - Upload any media files before referencing them in posts
210
  - Validate WordPress credentials before posting
211
  - Generate high-quality, relevant content
212
  - Handle errors gracefully
tools/wordpress_media.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from requests.auth import HTTPBasicAuth
3
+ from typing import Dict, Optional
4
+ import os
5
+ import mimetypes
6
+ from smolagents.tools import Tool
7
+
8
+
9
+ class WordPressMediaTool(Tool):
10
+ name = "wordpress_media"
11
+ description = "Uploads media files to WordPress and returns the attachment URL"
12
+ inputs = {
13
+ 'file_path': {'type': 'string', 'description': 'Local path to the media file to upload'},
14
+ 'title': {
15
+ 'type': 'string',
16
+ 'description': 'Title for the media attachment',
17
+ 'nullable': True
18
+ },
19
+ 'alt_text': {
20
+ 'type': 'string',
21
+ 'description': 'Alt text for the media attachment',
22
+ 'nullable': True
23
+ }
24
+ }
25
+ output_type = "object"
26
+
27
+ def __init__(self, wordpress_credentials):
28
+ super().__init__()
29
+ self.credentials = wordpress_credentials
30
+
31
+ def forward(self, file_path: str, title: str = None, alt_text: str = None) -> Dict:
32
+ """Uploads a media file to WordPress
33
+ Args:
34
+ file_path: Path to the media file
35
+ title: Optional title for the media attachment
36
+ alt_text: Optional alt text for the media attachment
37
+ Returns:
38
+ Dict containing the response from WordPress with media details
39
+ """
40
+ if not self.credentials:
41
+ return {"error": "WordPress credentials not configured"}
42
+
43
+ if not os.path.exists(file_path):
44
+ return {"error": f"File not found: {file_path}"}
45
+
46
+ api_url = f"{self.credentials['site_url']}/wp-json/wp/v2/media"
47
+ auth = HTTPBasicAuth(
48
+ self.credentials['username'], self.credentials['app_password'])
49
+
50
+ # Determine mime type
51
+ mime_type, _ = mimetypes.guess_type(file_path)
52
+ if not mime_type:
53
+ return {"error": "Could not determine file type"}
54
+
55
+ # Prepare headers
56
+ headers = {
57
+ 'Content-Type': mime_type,
58
+ 'Content-Disposition': f'attachment; filename="{os.path.basename(file_path)}"'
59
+ }
60
+
61
+ try:
62
+ # Upload file
63
+ with open(file_path, 'rb') as file:
64
+ response = requests.post(
65
+ api_url,
66
+ headers=headers,
67
+ auth=auth,
68
+ data=file
69
+ )
70
+ response.raise_for_status()
71
+ response_data = response.json()
72
+
73
+ # Update media properties if title or alt_text provided
74
+ if title or alt_text:
75
+ media_id = response_data['id']
76
+ update_url = f"{api_url}/{media_id}"
77
+ update_data = {}
78
+
79
+ if title:
80
+ update_data['title'] = {'rendered': title}
81
+ if alt_text:
82
+ update_data['alt_text'] = alt_text
83
+
84
+ if update_data:
85
+ update_response = requests.post(
86
+ update_url,
87
+ json=update_data,
88
+ auth=auth
89
+ )
90
+ update_response.raise_for_status()
91
+ response_data = update_response.json()
92
+
93
+ return {
94
+ "status": "success",
95
+ "attachment_id": response_data.get("id"),
96
+ "url": response_data.get("source_url"),
97
+ "title": response_data.get("title", {}).get("rendered"),
98
+ "alt_text": response_data.get("alt_text")
99
+ }
100
+
101
+ except requests.exceptions.RequestException as e:
102
+ print(f"Failed to upload media: {str(e)}")
103
+ return {"error": f"Failed to upload media: {str(e)}"}