ChandimaPrabath commited on
Commit
cd180fe
1 Parent(s): a6d862e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -134
app.py CHANGED
@@ -1,142 +1,108 @@
 
 
1
  import os
2
  import threading
3
- import requests
4
- from flask import Flask, request, jsonify
5
-
6
- from llm import generate_llm
7
- from sd import generate_sd
8
-
9
- GREEN_API_URL = os.getenv("GREEN_API_URL")
10
- GREEN_API_MEDIA_URL = os.getenv("GREEN_API_MEDIA_URL", "https://api.green-api.com")
11
- GREEN_API_TOKEN = os.getenv("GREEN_API_TOKEN")
12
- GREEN_API_ID_INSTANCE = os.getenv("GREEN_API_ID_INSTANCE")
13
- WEBHOOK_AUTH_TOKEN = os.getenv("WEBHOOK_AUTH_TOKEN")
14
- PORT = 7860
15
-
16
- if not all([GREEN_API_URL, GREEN_API_TOKEN, GREEN_API_ID_INSTANCE, WEBHOOK_AUTH_TOKEN]):
17
- raise ValueError("Environment variables are not set properly")
18
 
19
  app = Flask(__name__)
20
-
21
- def send_message(message_id, to_number, message, retries=3):
22
- """
23
- Send a text message using Green API with retry logic.
24
- """
25
- if to_number.endswith('@g.us'):
26
- chat_id = to_number
27
- else:
28
- chat_id = to_number
29
-
30
- url = f"{GREEN_API_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendMessage/{GREEN_API_TOKEN}"
31
- payload = {
32
- "chatId": chat_id,
33
- "message": message,
34
- "quotedMessageId": message_id,
 
 
 
 
 
 
35
  }
36
-
37
- for attempt in range(retries):
38
- try:
39
- response = requests.post(url, json=payload)
40
- response.raise_for_status()
41
- return response.json()
42
- except requests.RequestException as e:
43
- if attempt < retries - 1:
44
- continue
45
- return {"error": str(e)}
46
-
47
- def send_image(message_id, to_number, image_path, retries=3):
48
- """
49
- Send an image using Green API with retry logic.
50
- """
51
- if to_number.endswith('@g.us'):
52
- chat_id = to_number
53
- else:
54
- chat_id = to_number
55
-
56
- url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendFileByUpload/{GREEN_API_TOKEN}"
57
- payload = {'chatId': chat_id, 'caption': 'Here you go!', 'quotedMessageId': message_id}
58
- files = [('file', ('image.jpg', open(image_path, 'rb'), 'image/jpeg'))]
59
-
60
- for attempt in range(retries):
61
- try:
62
- response = requests.post(url, data=payload, files=files)
63
- response.raise_for_status()
64
- return response.json()
65
- except requests.RequestException as e:
66
- if attempt < retries - 1:
67
- continue
68
- return {"error": str(e)}
69
-
70
- def response_text(message_id, chat_id, prompt):
71
- """
72
- Generate a response using the LLM and send it to the user.
73
- """
74
- try:
75
- msg = generate_llm(prompt)
76
- send_message(message_id, chat_id, msg)
77
- except Exception as e:
78
- send_message(message_id, chat_id, "There was an error processing your request.")
79
-
80
- def handle_image_generation(message_id, chat_id, prompt):
81
- """
82
- Generate an image from the provided prompt and send it to the user.
83
- """
84
- try:
85
- image_data, image_path = generate_sd(prompt)
86
- if image_data:
87
- send_image(message_id, chat_id, image_path)
88
- else:
89
- send_message(message_id, chat_id, "Failed to generate image. Please try again later.")
90
- except Exception as e:
91
- send_message(message_id, chat_id, "There was an error generating the image. Please try again later.")
92
-
93
- @app.route('/', methods=['GET'])
94
  def index():
95
- """
96
- Basic endpoint to check if the script is running.
97
- """
98
- return "Server is running!"
99
-
100
- @app.route('/whatsapp', methods=['POST'])
101
- def whatsapp_webhook():
102
- """
103
- Handle incoming WhatsApp messages.
104
- """
105
- data = request.get_json()
106
- auth_header = request.headers.get('Authorization', '').strip()
107
-
108
- if auth_header != f"Bearer {WEBHOOK_AUTH_TOKEN}":
109
- return jsonify({"error": "Unauthorized"}), 403
110
-
111
- if data.get('typeWebhook') != 'incomingMessageReceived':
112
- return jsonify(success=True)
113
-
114
- try:
115
- chat_id = data['senderData']['chatId']
116
- message_id = data['idMessage']
117
- message_data = data.get('messageData', {})
118
-
119
- if 'textMessageData' in message_data:
120
- body = message_data['textMessageData']['textMessage'].strip()
121
- elif 'extendedTextMessageData' in message_data:
122
- body = message_data['extendedTextMessageData']['text'].strip()
123
- else:
124
- return jsonify(success=True)
125
-
126
- except KeyError as e:
127
- return jsonify({"error": f"Missing key in data: {e}"}), 200
128
-
129
- if body.lower().startswith('/imagine'):
130
- prompt = body.replace('/imagine', '').strip()
131
- if not prompt:
132
- send_message(message_id, chat_id, "Please provide a prompt after /imagine.")
133
- else:
134
- send_message(message_id, chat_id, "Generating...")
135
- threading.Thread(target=handle_image_generation, args=(message_id, chat_id, prompt)).start()
136
- else:
137
- threading.Thread(target=response_text, args=(message_id, chat_id, body)).start()
138
-
139
- return jsonify(success=True)
140
 
141
  if __name__ == '__main__':
142
- app.run(debug=True, port=PORT, host="0.0.0.0")
 
1
+ from flask import Flask, request, jsonify, send_file
2
+ from flask.templating import render_template
3
  import os
4
  import threading
5
+ import yaml
6
+ from image_payload_reader import read_payload_from_image
7
+ from telegram import start_telegram_bot
8
+ from utils import read_config
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  app = Flask(__name__)
11
+ templates_dir = "templates"
12
+
13
+ # Model for response
14
+ class ImageFile:
15
+ def __init__(self, image, yaml_data):
16
+ self.image = image
17
+ self.yaml = yaml_data
18
+
19
+ class ImageResponse:
20
+ def __init__(self, image_files):
21
+ self.image_files = image_files
22
+
23
+ def refresh_info():
24
+ config = read_config()
25
+ app_version = config['app']['version']
26
+ whatsapp_bot_enabled = config['app']['whatsapp_bot_enabled']
27
+ telegram_bot_enabled = config['app']['telegram_bot_enabled']
28
+ info = {
29
+ 'version': app_version,
30
+ 'whatsapp_bot_enabled': whatsapp_bot_enabled,
31
+ 'telegram_bot_enabled': telegram_bot_enabled,
32
  }
33
+ return info
34
+
35
+ def start_bots():
36
+ info = refresh_info()
37
+ telegram_bot_enabled = info['telegram_bot_enabled']
38
+
39
+ if telegram_bot_enabled:
40
+ start_telegram_bot()
41
+
42
+ # Note: WhatsApp bot functionality is not implemented in this Flask version
43
+
44
+ # Start the Telegram bot in a separate thread when the application starts
45
+ threading.Thread(target=start_bots).start()
46
+
47
+ # Function to fetch image files and corresponding YAML data from 'cache' directory
48
+ def fetch_image_files():
49
+ files = os.listdir('cache')
50
+ image_files = [f for f in files if f.endswith(('.jpg', '.jpeg', '.png'))]
51
+ response_data = []
52
+
53
+ for image_file in image_files:
54
+ yaml_file = image_file.rsplit('.', 1)[0] + '.yaml'
55
+ yaml_data = {}
56
+ if yaml_file in files:
57
+ with open(os.path.join('cache', yaml_file), 'r') as file:
58
+ yaml_data = yaml.safe_load(file)
59
+ response_data.append(ImageFile(image=image_file, yaml_data=yaml_data))
60
+
61
+ return response_data
62
+
63
+ @app.route('/')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  def index():
65
+ # Render the HTML template with fresh image data
66
+ image_data = fetch_image_files()
67
+ return render_template("index.html", image_data=image_data)
68
+
69
+ @app.route('/info')
70
+ def get_info():
71
+ info = refresh_info()
72
+ return jsonify(info)
73
+
74
+ @app.route('/images')
75
+ def get_images():
76
+ # Fetch fresh image data
77
+ image_data = fetch_image_files()
78
+ response_data = [img.__dict__ for img in image_data]
79
+ return jsonify(ImageResponse(response_data).__dict__)
80
+
81
+ @app.route('/cache/<image_name>')
82
+ def get_image(image_name):
83
+ file_path = os.path.join('cache', image_name)
84
+ if os.path.exists(file_path):
85
+ return send_file(file_path)
86
+ return jsonify({"error": "File not found"}), 404
87
+
88
+ @app.route('/statics/<image_name>')
89
+ def get_static_image(image_name):
90
+ file_path = os.path.join('statics', image_name)
91
+ if os.path.exists(file_path):
92
+ return send_file(file_path)
93
+ return jsonify({"error": "File not found"}), 404
94
+
95
+ @app.route('/yaml/<image_name>')
96
+ def get_embedded_yaml(image_name):
97
+ file_path = os.path.join('cache', image_name)
98
+ if not os.path.exists(file_path):
99
+ return jsonify({"error": "Image file not found"}), 404
100
+
101
+ # Use the function to read YAML payload from image metadata
102
+ yaml_payload = read_payload_from_image(file_path)
103
+ if yaml_payload:
104
+ return jsonify(yaml_payload)
105
+ return jsonify({"error": "No YAML payload found in the image metadata"}), 404
 
 
 
 
106
 
107
  if __name__ == '__main__':
108
+ app.run(debug=True, port=7860, host="0.0.0.0")