Skip to content

Instantly share code, notes, and snippets.

@mewmix
Created August 18, 2023 03:07
Show Gist options
  • Save mewmix/e69e9a870179b435b8d6ee127f8443b3 to your computer and use it in GitHub Desktop.
Save mewmix/e69e9a870179b435b8d6ee127f8443b3 to your computer and use it in GitHub Desktop.
mockup api server
from flask import Flask, request, jsonify, send_file, render_template
import requests
import json
import datetime
from PIL import Image, ImageDraw, ImageFont
import io
import os
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
PINATA_API_URL = "https://api.pinata.cloud/pinning/pinFileToIPFS"
PINATA_API_KEY = "" # Replace with your actual Pinata
# Route to pin a file to IPFS
@app.route('/')
def index():
return render_template('index.html')
@app.route('/pin', methods=['POST'])
def pin_to_ipfs():
try:
file = request.files['file']
headers = {
"accept": "application/json",
"authorization": f"Bearer {PINATA_API_KEY}"
}
files = {
"file": (file.filename, file.stream, file.content_type)
}
response = requests.post(PINATA_API_URL, files=files, headers=headers)
response_json = response.json()
if response.status_code == 200:
addresses = request.form # Get addresses from the request's form data
log_pin_data(response_json, addresses) # Log pin data and addresses to JSON file
return jsonify(response_json), 200
else:
return jsonify(response_json), response.status_code
except Exception as e:
return str(e), 500
# Function to log pin data and addresses to a JSON file
def log_pin_data(pin_data, addresses):
log_entry = {
"timestamp": str(datetime.datetime.now()),
"pin_data": pin_data,
"addresses": addresses
}
with open("pin_data_log.json", "a") as log_file:
json.dump(log_entry, log_file)
log_file.write('\n')
# Route to accept Tezos and Twitter addresses
@app.route('/add_addresses', methods=['POST'])
def add_addresses():
try:
data = request.json
tezos_address = data.get('tezos_address')
twitter_address = data.get('twitter_address')
# Load existing addresses or initialize an empty list
existing_addresses = load_addresses()
existing_addresses.append({"tezos_address": tezos_address, "twitter_address": twitter_address})
# Store the updated addresses
store_addresses(existing_addresses)
return jsonify({"message": "Addresses added successfully"}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
# Function to load addresses from the JSON file
def load_addresses():
try:
with open("pin_data_log.json") as log_file:
return json.load(log_file).get("addresses", [])
except (FileNotFoundError, json.JSONDecodeError):
return []
# Function to store addresses in the JSON file
def store_addresses(addresses):
with open("pin_data_log.json", "r+") as log_file:
data = json.load(log_file)
data["addresses"] = addresses
log_file.seek(0)
json.dump(data, log_file, indent=4)
log_file.truncate()
@app.route('/generate_image', methods=['POST'])
def generate_image():
social_score = int(request.form.get('social_score', 0))
# Get the uploaded image
uploaded_image = request.files['uploaded_image']
# Determine the background image based on the social score range
if 300 <= social_score <= 499:
background_image_path = 'foreground_300.png'
elif social_score >= 500:
background_image_path = 'foreground_500.png'
else:
background_image_path = 'foreground_0.png'
# Load the selected background image
background_image = Image.open(background_image_path).convert("RGBA")
# Load and convert the uploaded image to RGBA
uploaded_image = Image.open(uploaded_image).convert("RGBA")
uploaded_image = uploaded_image.resize(background_image.size, Image.ANTIALIAS)
# Create a new image to combine the background and uploaded images
combined_image = Image.new('RGBA', background_image.size)
# Paste the uploaded image onto the combined image first
combined_image.paste(uploaded_image, (0, 0), uploaded_image)
# Then paste the background image on top of the uploaded image
combined_image.paste(background_image, (0, 0), background_image)
# Create a drawing object
draw = ImageDraw.Draw(combined_image)
# Load a font (replace 'kremlin.ttf' with your font path)
font = ImageFont.truetype('kremlin.ttf', 40)
# Calculate text size
text = f'{social_score}'
text_size = draw.textsize(text, font=font)
# Define the position to place the text (bottom left corner)
text_position = (65, combined_image.height - text_size[1] - 60) # Adjust margins as needed
# Draw the text on the image
draw.text(text_position, text, fill=(255, 255, 255), font=font)
# Generate a unique filename for the image
image_filename = f'generated_image_{social_score}.png'
# Save the combined image to a temporary location
temp_image_path = os.path.join('/var/www/html/temp/', image_filename)
combined_image.convert('RGB').save(temp_image_path, format='PNG')
web_path = f'http://173.255.220.99:/temp/{image_filename}'
# Return the URL of the saved image in the response
image_url = f'{web_path}'
return image_url
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000,debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment