import os import json import requests import glob import exifread from PIL import Image from PIL.ExifTags import TAGS from PIL.PngImagePlugin import PngImageFile, PngInfo def confirm(): confirmMsg = input("[y]es or [n]o ") if confirmMsg == 'y' or confirmMsg == 'yes': return True elif confirmMsg == 'n' or confirmMsg == 'no': return False else: print("\n Invalid Option. Please Enter a Valid Option.") return confirm() return False def load_config(file_path): with open(file_path, "r") as config_file: config_data = json.load(config_file) return config_data def getTags(file_path): try: file = open(file_path,'r') fileContent = file.read() file.close except: fileContent = '' return fileContent def getImages(dir): result = glob.glob(dir + '/*.jpg') return result def getItemDescription(filename): img = Image.open(filename) exif_data = img._getexif() imageDescription = "" if exif_data: for tag, value in exif_data.items(): tag_name = TAGS.get(tag, tag) if str(tag_name) == "ImageDescription": imageDescription = str(value) break else: imageDescription = "This image has no description. Please let me know so that I can update it." else: raise ValueError("No EXIF data found.") return imageDescription def getPostText(filename): postText = "" tags = getTags("tags.txt") date = "" cam = "" title = "" img = Image.open(filename) exif_data = img._getexif() if exif_data: for tag, value in exif_data.items(): tag_name = TAGS.get(tag, tag) if tag_name == "DateTimeOriginal": dateTime = value year = dateTime[:4] month = dateTime[5:7] date = "🗓 " + year + "-" + month if tag_name == "Make": cam += "📸 " + value if cam != "" and tag_name == "Model": cam += " " + value if tag_name == "Object Name": print(value) title = value else: raise ValueError("No EXIF data found.") if date != "": postText = date if cam != "": if postText != "": postText += " || " postText += cam if title != "": postText += "\n\r\n\r" + title elif title == "": print(f"No post Text found. Do you want to add a post text for file " + os.path.basename(filename) + "?") if confirm(): ownPostText = input("Post text:") ownPostText.encode('utf-8') postText += "\n\r\n\r" + ownPostText postText += "\n\r\n\r" + tags return postText def mediaUpload(access_token, url, file, itemDescription): api_url = url + "/api/v1/media" headers = { "Authorization": f"Bearer {access_token}" } try: with open(file, "rb") as imageFile: f = { "file": (file, imageFile) } data = { "description": itemDescription.encode('utf-8') } response = requests.post(api_url, headers=headers, files=f, data=data) response.raise_for_status() try: data = response.json() return(data) except json.decoder.JSONDecodeError: print("API response contains non-valid JSON data:") print(response.text) except requests.exceptions.RequestException as e: print(f"An error occurred during the API call: {e}") def createNewPost(access_token, url, ImageID, ImageDescription): api_url = url + "/api/v1/statuses" ImageIDs = ImageID.split(",") ImageIDsInt = list(map(int, ImageIDs)) headers = { "Authorization": f"Bearer {access_token}" } data = { "status": ImageDescription, "media_ids": ImageIDsInt } try: response = requests.post(api_url, headers=headers, json=data) try: responsedata = response.json() return(responsedata) except json.decoder.JSONDecodeError: print("API response contains non-valid JSON data:") print(response.text) except requests.exceptions.RequestException as e: print(f"An error occurred during the API call: {e}") def sendImages(Token, url, imagedir, uploadType, deleteFile): files = getImages(imagedir) if not files: raise ValueError("No file found.") postText = "" newFileID = "" itemDescription = "" postText = "" for f in files: itemDescription = getItemDescription(f) newFile = mediaUpload(Token, url, f, itemDescription) if uploadType == 0: postText = getPostText(f) newFileID = newFile.get("id") print(f"----------------------------------------") print(f"Post Summary: ") print(f"ImageID: " + newFileID) print(f"Image Description: " + newFile.get("description")) print(f"Post Text: " + postText) print(f"----------------------------------------") print(f"Do you want to Publish this?") if confirm(): createNewPost(Token, url, newFileID, postText) else: deleteFile = False print(f"File upload aborted.") else: if postText == "": postText = getPostText(f) if newFileID != "": newFileID = newFileID + "," + newFile.get("id") else: newFileID = newFile.get("id") if uploadType == 1: createNewPost(Token, url, newFileID, postText) if deleteFile: for f in files: if os.path.exists(f): os.remove(f) return True if __name__ == "__main__": config_file_path = "config.json" config = load_config(config_file_path) url = config.get("server_url") accessToken = config.get("access_token") imagedir = config.get("image_path") uploadType = config.get("upload_type") deleteFile = config.get("delete_file") try: sendImages(accessToken, url, imagedir, uploadType, deleteFile) except ValueError as e: print(f"Error while uploading the image: {e}")