Geek7 commited on
Commit
c813777
·
verified ·
1 Parent(s): 715d5c0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -107
app.py CHANGED
@@ -1,114 +1,53 @@
1
- from flask import Flask, request, jsonify, send_file
2
- from flask_cors import CORS
3
  import os
4
- import subprocess
5
- from huggingface_hub import InferenceClient
6
- from io import BytesIO
7
- from PIL import Image
8
 
9
- # Initialize the Flask app
10
  app = Flask(__name__)
11
- CORS(app) # Enable CORS for all routes
12
 
13
- # Initialize the InferenceClient with your Hugging Face token
14
- HF_TOKEN = os.environ.get("HF_TOKEN") # Ensure to set your Hugging Face token in the environment
15
- client = InferenceClient(token=HF_TOKEN)
16
-
17
- # Hardcoded negative prompt
18
- NEGATIVE_PROMPT_FINGERS = """2D,missing fingers, extra fingers, elongated fingers, fused fingers,
19
- mutated fingers, poorly drawn fingers, disfigured fingers,
20
- too many fingers, deformed hands, extra hands, malformed hands,
21
- blurry hands, disproportionate fingers"""
22
 
 
23
  @app.route('/')
24
  def home():
25
- return "Welcome to the Image Background Remover!"
26
-
27
- # Simple content moderation function
28
- def is_prompt_explicit(prompt):
29
- # Streamlined keyword list to avoid unnecessary restrictions
30
- explicit_keywords = [
31
- "sexual", "porn", "hentai", "fetish", "nude", "provocative", "obscene", "vulgar", "intimate", "kinky", "hardcore",
32
- "threesome", "orgy", "masturbation", "genital", "suicide",
33
- "self-harm", "depression", "kill myself", "worthless"
34
- ]
35
- for keyword in explicit_keywords:
36
- if keyword.lower() in prompt.lower():
37
- return True
38
- return False
39
-
40
- # Function to generate an image from a text prompt
41
- def generate_image(prompt, negative_prompt=None, height=512, width=512, model="stabilityai/stable-diffusion-2-1", num_inference_steps=50, guidance_scale=7.5, seed=None):
42
- try:
43
- # Generate the image using Hugging Face's inference API with additional parameters
44
- image = client.text_to_image(
45
- prompt=prompt,
46
- negative_prompt=NEGATIVE_PROMPT_FINGERS,
47
- height=height,
48
- width=width,
49
- model=model,
50
- num_inference_steps=num_inference_steps, # Control the number of inference steps
51
- guidance_scale=guidance_scale, # Control the guidance scale
52
- seed=seed # Control the seed for reproducibility
53
- )
54
- return image # Return the generated image
55
- except Exception as e:
56
- print(f"Error generating image: {str(e)}")
57
- return None
58
-
59
- # Flask route for the API endpoint to generate an image
60
- @app.route('/generate_image', methods=['POST'])
61
- def generate_api():
62
- data = request.get_json()
63
-
64
- # Extract required fields from the request
65
- prompt = data.get('prompt', '')
66
- negative_prompt = data.get('negative_prompt', None)
67
- height = data.get('height', 1024) # Default height
68
- width = data.get('width', 720) # Default width
69
- num_inference_steps = data.get('num_inference_steps', 50) # Default number of inference steps
70
- guidance_scale = data.get('guidance_scale', 7.5) # Default guidance scale
71
- model_name = data.get('model', 'stabilityai/stable-diffusion-2-1') # Default model
72
- seed = data.get('seed', None) # Seed for reproducibility, default is None
73
-
74
- if not prompt:
75
- return jsonify({"error": "Prompt is required"}), 400
76
-
77
- try:
78
- # Check for explicit content
79
- if is_prompt_explicit(prompt):
80
- # Return the pre-defined "thinkgood.png" image
81
- return send_file(
82
- "nsfw.jpg",
83
- mimetype='image/png',
84
- as_attachment=False,
85
- download_name='thinkgood.png'
86
- )
87
-
88
- # Call the generate_image function with the provided parameters
89
- image = generate_image(prompt, negative_prompt, height, width, model_name, num_inference_steps, guidance_scale, seed)
90
-
91
- if image:
92
- # Save the image to a BytesIO object
93
- img_byte_arr = BytesIO()
94
- image.save(img_byte_arr, format='PNG') # Convert the image to PNG
95
- img_byte_arr.seek(0) # Move to the start of the byte stream
96
-
97
- # Send the generated image as a response
98
- return send_file(
99
- img_byte_arr,
100
- mimetype='image/png',
101
- as_attachment=False, # Send the file as an attachment
102
- download_name='generated_image.png' # The file name for download
103
- )
104
- else:
105
- return jsonify({"error": "Failed to generate image"}), 500
106
- except Exception as e:
107
- print(f"Error in generate_api: {str(e)}") # Log the error
108
- return jsonify({"error": str(e)}), 500
109
-
110
- # Add this block to make sure your app runs when called
111
- if __name__ == "__main__":
112
- subprocess.Popen(["python", "wk.py"]) # Start awake.py
113
-
114
- app.run(host='0.0.0.0', port=7860) # Run directly if needed for testing
 
1
+ from flask import Flask, request, jsonify, redirect, render_template
2
+ import requests
3
  import os
4
+ from flask_cors import CORS
 
 
 
5
 
 
6
  app = Flask(__name__)
7
+ CORS(app)
8
 
9
+ # Access the secrets from environment variables in Hugging Face
10
+ CLIENT_ID = os.getenv('v1') # Your Client ID
11
+ CLIENT_SECRET = os.getenv('v2') # Your Client Secret
12
+ REDIRECT_URI = 'http://127.0.0.1:5000/callback'
13
+ SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize"
14
+ SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
15
+ SPOTIFY_API_URL = "https://api.spotify.com/v1"
 
 
16
 
17
+ # Home route
18
  @app.route('/')
19
  def home():
20
+ return render_template('index.html')
21
+
22
+ # Get Spotify authorization URL
23
+ @app.route('/login')
24
+ def login():
25
+ scopes = "user-read-private user-read-email"
26
+ auth_url = f"{SPOTIFY_AUTH_URL}?response_type=code&client_id={CLIENT_ID}&scope={scopes}&redirect_uri={REDIRECT_URI}"
27
+ return redirect(auth_url)
28
+
29
+ # Callback to handle the access token
30
+ @app.route('/callback')
31
+ def callback():
32
+ code = request.args.get('code')
33
+ auth_response = requests.post(SPOTIFY_TOKEN_URL, data={
34
+ "grant_type": "authorization_code",
35
+ "code": code,
36
+ "redirect_uri": REDIRECT_URI,
37
+ "client_id": CLIENT_ID,
38
+ "client_secret": CLIENT_SECRET,
39
+ })
40
+ response_data = auth_response.json()
41
+ access_token = response_data.get("access_token")
42
+ return jsonify({"access_token": access_token})
43
+
44
+ # Fetch data from Spotify API
45
+ @app.route('/api/podcasts')
46
+ def get_podcasts():
47
+ token = request.args.get('token') # Pass access_token as a query param
48
+ headers = {"Authorization": f"Bearer {token}"}
49
+ response = requests.get(f"{SPOTIFY_API_URL}/browse/categories/podcasts", headers=headers)
50
+ return jsonify(response.json())
51
+
52
+ if __name__ == '__main__':
53
+ app.run(debug=True)