File size: 2,061 Bytes
a16b74a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Your url for ST will be something like this:
# https://username-spaceName.hf.space/proxy/anthropic/v1
# Streaming is not supported


import logging
import json
from flask import Flask, request, Response
import requests

app = Flask(__name__)

# Configure the logging level
app.logger.setLevel(logging.INFO)

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
def relay_request(path):
    # Extract the base URL to relay requests
    base_url = 'https://username84-g.hf.space'  # Replace with the URL you want to relay requests to

    # Prepare the relay URL by appending the path from the original request
    relay_url = base_url + '/' + path

    # Apparently the original headers contain you IP, so I'm getting only the necessary info
    headers_ = dict()
    
    # So far I only saw ST sending the API through the headers, let me know if you find something else.
    if 'Content-Type' in request.headers:
        headers_['Content-Type'] = request.headers['Content-Type']
    if 'x-api-key' in request.headers:
        headers_['x-api-key'] = request.headers['x-api-key']

    # app.logger.info(headers_)
    
    # If post includes the json data
    if request.method == 'POST':
        response = requests.request(
            method='POST',
            url=relay_url,
            headers=headers_,
            json=json.loads(request.get_data()),
            allow_redirects=False # Idk if this is needed, GPT added it and it works, so whatever
        )
    else:
        response = requests.request(
            method=request.method,
            url=relay_url,
            headers=headers_,
            allow_redirects=False # Idk if this is needed, GPT added it and it works, so whatever
        )
        

    # Prepare the response to return to the original API call
    headers = [(name, value) for name, value in response.headers.items()]
    return Response(response.content, response.status_code, headers)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)