measmonysuon commited on
Commit
24ea1ea
1 Parent(s): bf2577c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -19
app.py CHANGED
@@ -2,7 +2,8 @@ import gradio as gr
2
  from gradio_client import Client
3
  import os
4
  import logging
5
- from urllib.parse import parse_qs, urlparse
 
6
 
7
  # Initialize the client for image generation
8
  client_image = Client("mukaist/DALLE-4K")
@@ -21,6 +22,9 @@ DEFAULT_STYLE = "3840 x 2160"
21
  logging.basicConfig(level=logging.INFO)
22
  logger = logging.getLogger(__name__)
23
 
 
 
 
24
  def generate_image(prompt, resolution_key, style=DEFAULT_STYLE):
25
  resolution = resolutions.get(resolution_key, (1024, 1024))
26
  width, height = resolution
@@ -45,12 +49,48 @@ def generate_image(prompt, resolution_key, style=DEFAULT_STYLE):
45
  logger.error(f"Error generating image: {e}")
46
  return None
47
 
48
- def gradio_interface(prompt, resolution_key):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  result = generate_image(prompt, resolution_key)
50
 
51
  if result and result[0]:
52
  file_path = result[0][0].get('image')
53
  if file_path and os.path.exists(file_path):
 
 
54
  return file_path, "The image was generated successfully."
55
  else:
56
  return None, "The image file is not available. Please try again later."
@@ -80,12 +120,21 @@ def create_gradio_interface(username):
80
  result_output = gr.Image(label="Generated Image", type="pil")
81
  message_output = gr.Textbox(label="Result", placeholder="Results will be shown here", interactive=False)
82
 
 
 
 
 
83
  # Set up interaction
84
  generate_button.click(
85
- fn=lambda prompt, resolution_key: gradio_interface(prompt, resolution_key),
86
  inputs=[prompt_input, resolution_dropdown],
87
  outputs=[result_output, message_output]
88
  )
 
 
 
 
 
89
 
90
  gr.HTML("""
91
  <style>
@@ -101,19 +150,6 @@ def launch_gradio(username):
101
  interface = create_gradio_interface(username)
102
  interface.launch()
103
 
104
- def extract_username_from_url(url):
105
- parsed_url = urlparse(url)
106
- params = parse_qs(parsed_url.query)
107
- logger.debug(f"Parsed URL parameters: {params}") # Debugging information
108
- return params.get('username', ["Guest"])[0]
109
-
110
- def get_username_from_url(url):
111
- # Extract username from the actual URL
112
- username = extract_username_from_url(url)
113
- logger.info(f"Extracted username: {username}")
114
- return username
115
-
116
- # Replace this URL with your actual URL where the Gradio app is hosted
117
- url = 'https://measmonysuon-imagen.hf.space/?username=Guest' # This should be dynamically obtained if needed
118
- username = get_username_from_url(url)
119
- launch_gradio(username)
 
2
  from gradio_client import Client
3
  import os
4
  import logging
5
+ import sqlite3
6
+ import requests
7
 
8
  # Initialize the client for image generation
9
  client_image = Client("mukaist/DALLE-4K")
 
22
  logging.basicConfig(level=logging.INFO)
23
  logger = logging.getLogger(__name__)
24
 
25
+ # Initialize database
26
+ db_path = 'C:/Users/Administrator/Desktop/TGBoot/photo2prompt_db/users.db'
27
+
28
  def generate_image(prompt, resolution_key, style=DEFAULT_STYLE):
29
  resolution = resolutions.get(resolution_key, (1024, 1024))
30
  width, height = resolution
 
49
  logger.error(f"Error generating image: {e}")
50
  return None
51
 
52
+ def update_user_points(username, points):
53
+ """Updates the user's points in the database."""
54
+ with sqlite3.connect(db_path) as conn:
55
+ cursor = conn.cursor()
56
+ cursor.execute('''
57
+ INSERT INTO users (username, points) VALUES (?, ?)
58
+ ON CONFLICT(username) DO UPDATE SET points = points + ?
59
+ ''', (username, points, points))
60
+ conn.commit()
61
+ logger.info(f"User with username {username} had their points updated by {points}.")
62
+
63
+ def notify_webhook(username):
64
+ """Notify the webhook server about the points update."""
65
+ webhook_url = "http://65.108.76.174:5000/update_points"
66
+ payload = {'username': username, 'points': 10} # Adjust payload as necessary
67
+ try:
68
+ response = requests.post(webhook_url, json=payload)
69
+ response.raise_for_status()
70
+ logger.info(f"Webhook notification sent successfully. Response: {response.status_code}")
71
+ except requests.RequestException as e:
72
+ logger.error(f"Error sending webhook notification: {e}")
73
+
74
+ def get_user_points(username):
75
+ """Retrieve user points from the Flask server."""
76
+ webhook_url = "http://65.108.76.174:5000/get_points"
77
+ params = {'username': username}
78
+ try:
79
+ response = requests.get(webhook_url, params=params)
80
+ response.raise_for_status()
81
+ return response.json()
82
+ except requests.RequestException as e:
83
+ logger.error(f"Error fetching user points: {e}")
84
+ return {"error": "Failed to retrieve user points"}
85
+
86
+ def gradio_interface(prompt, resolution_key, username):
87
  result = generate_image(prompt, resolution_key)
88
 
89
  if result and result[0]:
90
  file_path = result[0][0].get('image')
91
  if file_path and os.path.exists(file_path):
92
+ update_user_points(username, 10) # Award 10 points for each image generated
93
+ notify_webhook(username) # Notify the webhook server
94
  return file_path, "The image was generated successfully."
95
  else:
96
  return None, "The image file is not available. Please try again later."
 
120
  result_output = gr.Image(label="Generated Image", type="pil")
121
  message_output = gr.Textbox(label="Result", placeholder="Results will be shown here", interactive=False)
122
 
123
+ # Button to get user points
124
+ get_points_button = gr.Button("Get Points")
125
+ points_output = gr.Textbox(label="User Points", placeholder="User points will be displayed here", interactive=False)
126
+
127
  # Set up interaction
128
  generate_button.click(
129
+ fn=lambda prompt, resolution_key: gradio_interface(prompt, resolution_key, username),
130
  inputs=[prompt_input, resolution_dropdown],
131
  outputs=[result_output, message_output]
132
  )
133
+
134
+ get_points_button.click(
135
+ fn=lambda: get_user_points(username),
136
+ outputs=points_output
137
+ )
138
 
139
  gr.HTML("""
140
  <style>
 
150
  interface = create_gradio_interface(username)
151
  interface.launch()
152
 
153
+ if __name__ == '__main__':
154
+ # Launch Gradio with a default username
155
+ launch_gradio("Guest")