Comments (3)
Thank you for posting this, I've updated your code to get something working for current danbooru instances:
import hashlib
import json
import requests
def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128): # Maybe try chunking it higher for faster speeds..?
h = hash_factory()
with open(filename,'rb') as f:
while chunk := f.read(chunk_num_blocks*h.block_size):
h.update(chunk)
return h.hexdigest()
class danbooru():
# Updated for 29th of October 2023
def __init__(self, login, api_key, base_url):
"Must have all 3 values filled to work"
# Example danbooru("username","7Fi5AkBieaR83aQavLBbps2t","https://danbooru.selfhosted.org")
self.login = login
self.api_key = api_key
self.base_url = base_url
self.fn = "" # Filename not set until create post
def create_post(self, filename, tag_string, rating, source):
"Upload the image"
self.fn = filename
if self.search_md5() == -1: # If image not found, upload
media_asset_id = self.upload_image()
image_id = self.search_md5() # get image ID (even if it was uploaded)
self.upload_to_post(media_asset_id, image_id, tag_string, rating, source)
def upload_image(self):
"Upload the image with the tags given and the other information given"
files = {'upload[files][0]': open(self.fn, 'rb')}
url = self.base_url + "/uploads.json?api_key={}&login={}".format(self.api_key,self.login)
response = requests.post(url, files=files)
if response.status_code == 201:
print(response.json())
return response.json()["id"]
else:
print(response.json())
quit(1)
def search_md5(self):
"Searches danbooru instance with md5sum to get the id value"
md5 = checksum(self.fn)
url = self.base_url + "/uploads.json?search[media_assets][md5]={}&api_key={}&login={}".format(md5,self.api_key,self.login)
print(url)
response = requests.get(url)
if response.status_code == 200:
print(response.json()[0]["upload_media_assets"][0]["media_asset"]["id"])
return response.json()[0]["upload_media_assets"][0]["media_asset"]["id"]
else if response.status_code == 304:
print("Image not uploaded before!")
return -1
else:
print(response.json())
quit(1)
def upload_to_post(self, media_asset_id, image_id, tag_string, rating, source):
url = self.base_url + "/posts.json?api_key={}&login={}".format(self.api_key,self.login)
params = {"post[tag_string]": tag_string,
"post[rating]": rating, # rating [g -> general ,s -> sensitive,q -> questionable, e -> explicit]
"post[source]": source,
"media_asset_id": image_id,
"upload_media_asset_id": media_asset_id, # NOT SURE WHY THIS HAS TO BE DONE!!?!
#"post[artist_commentary_title]": todo (want to import via pixiv api)
#"post[artist_commentary_desc]": todo
}
print(params)
response = requests.post(url, params=params)
print(response)
if response.status_code == 201:
print("Post Creation Success")
else:
print("Failed to create post")
Example:
# (paste the code above)
...
DANBOORU_API_KEY = "yjtgDWgKryhECUFU34e1W2hs"
DANBOORU_URL = "https://danbooru.example.moe"
LOGIN = "641i130"
booru = danbooru(LOGIN,DANBOORU_API_KEY,DANBOORU_URL)
booru.create_post("./1234567_p0.jpg","one two three four","g","https://www.pixiv.net/en/artworks/1234567")
Updated. It now works fully. Had to make it 201 because it returns CREATED.
from pybooru.
I hope you found a solution for your problem, I will just post the code I used here so people in the future may have it a bit easier to reverse engineer that again
class danbooru():
def __init__(self, config):
"""
:param config: Config File with username, password and Base URL
{
"username":"admin",
"password":"1234",
"base_url":"topdesk.host"
}
"""
self.username = config["username"]
self.api_key = config["api_key"]
self.base_url = config["base_url"]
self.basic = HTTPBasicAuth(self.username, self.api_key)
def create_post(self, filename=None, tag_string="", rating="s", source=None):
image_id = self._upload_image(filename=filename)
self._upload_to_post(tag_string=tag_string, rating=rating, image_id=image_id)
def _upload_image(self, filename=None):
files = {'upload[files][0]': open(filename, 'rb')}
url = self.base_url + "/uploads.json"
response = requests.request("POST", url, auth=self.basic, files=files)
if response.status_code == 201:
return response.json()["id"]
else:
pprint(response.json())
quit(1)
def _upload_to_post(self, image_id=None, tag_string="", rating="s", source=None):
url = self.base_url + "/posts"
params = {"post[tag_string]": tag_string,
"post[rating]": rating,
"post[source]": source,
"upload_media_asset_id": image_id}
response = requests.request("POST", url, auth=self.basic, params=params)
if response.status_code == 200:
logger.info("Post Creation Success")
else:
logger.error("Failed to create post")
pprint(logger.json())
from pybooru.
Maybe we can get this into the pybooru library? Not sure how to do this, but maybe I'll make a pull request if I have time on the weekend.
from pybooru.
Related Issues (20)
- Create tests
- Add lolibooru to default site list
- Testing with sankaku sites
- Update docs to show Moebooru API versions
- JSON request error (yandere & konachan) HOT 1
- [TypeError]: list indices must be integers or slices, not str HOT 1
- feature_add(post_id) not working HOT 4
- I cant add more then 1 tag HOT 1
- Redirect travis-ci links to travis-ci.com and update README
- Danbooru client.favorite_remove(post_id) bug HOT 1
- Support Danbooru "Common Search Parameters" ; at least 'page' and 'limit' HOT 1
- Replace Travis CI with a GitHub Workflow
- Update setup.py, add pyproject.toml and use setup.cfg for metadata also remove unncecesary files
- Remove `bdist_wheel` from `setup.cfg` because since we will no longer support py2
- Danbooru CSFR problem HOT 2
- Add Dependabot updates
- Organize GitHub labels
- Move to asyncio & aiohttp? HOT 2
- danbooru hot page support
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pybooru.