Aleksmorshen commited on
Commit
c7cde40
·
verified ·
1 Parent(s): 5758652

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -81
app.py CHANGED
@@ -17,7 +17,7 @@ from huggingface_hub.utils import RepositoryNotFoundError
17
 
18
  from aiogram import Bot, Dispatcher, types, F
19
  from google import genai
20
- from google.genai import types
21
 
22
  BOT_TOKEN = os.getenv("BOT_TOKEN", "7566834146:AAGiG4MaTZZvvtVsqEJVG5SYK5hUlc_Ewo")
23
  HOST = '0.0.0.0'
@@ -41,10 +41,8 @@ visitor_data_cache = {}
41
  def download_data_from_hf():
42
  global visitor_data_cache
43
  if not HF_TOKEN_READ:
44
- logging.warning("HF_TOKEN_READ not set. Skipping Hugging Face download.")
45
  return False
46
  try:
47
- logging.info(f"Attempting to download {HF_DATA_FILE_PATH} from {REPO_ID}...")
48
  hf_hub_download(
49
  repo_id=REPO_ID,
50
  filename=HF_DATA_FILE_PATH,
@@ -55,20 +53,17 @@ def download_data_from_hf():
55
  force_download=True,
56
  etag_timeout=10
57
  )
58
- logging.info("Data file successfully downloaded from Hugging Face.")
59
  with _data_lock:
60
  try:
61
  with open(DATA_FILE, 'r', encoding='utf-8') as f:
62
  visitor_data_cache = json.load(f)
63
- logging.info("Successfully loaded downloaded data into cache.")
64
  except (FileNotFoundError, json.JSONDecodeError) as e:
65
- logging.error(f"Error reading downloaded data file: {e}. Starting with empty cache.")
66
  visitor_data_cache = {}
67
  return True
68
  except RepositoryNotFoundError:
69
- logging.error(f"Hugging Face repository '{REPO_ID}' not found. Cannot download data.")
70
  except Exception as e:
71
- logging.error(f"Error downloading data from Hugging Face: {e}")
72
  return False
73
 
74
  def load_visitor_data():
@@ -78,15 +73,11 @@ def load_visitor_data():
78
  try:
79
  with open(DATA_FILE, 'r', encoding='utf-8') as f:
80
  visitor_data_cache = json.load(f)
81
- logging.info("Visitor data loaded from local JSON.")
82
  except FileNotFoundError:
83
- logging.warning(f"{DATA_FILE} not found locally. Starting with empty data.")
84
  visitor_data_cache = {}
85
  except json.JSONDecodeError:
86
- logging.error(f"Error decoding {DATA_FILE}. Starting with empty data.")
87
  visitor_data_cache = {}
88
  except Exception as e:
89
- logging.error(f"Unexpected error loading visitor data: {e}")
90
  visitor_data_cache = {}
91
  return visitor_data_cache
92
 
@@ -96,17 +87,14 @@ def save_visitor_data(data):
96
  visitor_data_cache.update(data)
97
  with open(DATA_FILE, 'w', encoding='utf-8') as f:
98
  json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4)
99
- logging.info(f"Visitor data successfully saved to {DATA_FILE}.")
100
  upload_data_to_hf_async()
101
  except Exception as e:
102
- logging.error(f"Error saving visitor data: {e}")
103
 
104
  def upload_data_to_hf():
105
  if not HF_TOKEN_WRITE:
106
- logging.warning("HF_TOKEN_WRITE not set. Skipping Hugging Face upload.")
107
  return
108
  if not os.path.exists(DATA_FILE):
109
- logging.warning(f"{DATA_FILE} does not exist. Skipping upload.")
110
  return
111
 
112
  try:
@@ -114,10 +102,8 @@ def upload_data_to_hf():
114
  with _data_lock:
115
  file_content_exists = os.path.getsize(DATA_FILE) > 0
116
  if not file_content_exists:
117
- logging.warning(f"{DATA_FILE} is empty. Skipping upload.")
118
  return
119
 
120
- logging.info(f"Attempting to upload {DATA_FILE} to {REPO_ID}/{HF_DATA_FILE_PATH}...")
121
  api.upload_file(
122
  path_or_fileobj=DATA_FILE,
123
  path_in_repo=HF_DATA_FILE_PATH,
@@ -126,9 +112,8 @@ def upload_data_to_hf():
126
  token=HF_TOKEN_WRITE,
127
  commit_message=f"Update visitor data {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
128
  )
129
- logging.info("Visitor data successfully uploaded to Hugging Face.")
130
  except Exception as e:
131
- logging.error(f"Error uploading data to Hugging Face: {e}")
132
 
133
  def upload_data_to_hf_async():
134
  upload_thread = threading.Thread(target=upload_data_to_hf, daemon=True)
@@ -136,11 +121,9 @@ def upload_data_to_hf_async():
136
 
137
  def periodic_backup():
138
  if not HF_TOKEN_WRITE:
139
- logging.info("Periodic backup disabled: HF_TOKEN_WRITE not set.")
140
  return
141
  while True:
142
  time.sleep(3600)
143
- logging.info("Initiating periodic backup...")
144
  upload_data_to_hf()
145
 
146
  def verify_telegram_data(init_data_str):
@@ -163,13 +146,12 @@ def verify_telegram_data(init_data_str):
163
  auth_date = int(parsed_data.get('auth_date', [0])[0])
164
  current_time = int(time.time())
165
  if current_time - auth_date > 86400:
166
- logging.warning(f"Telegram InitData is older than 1 hour (Auth Date: {auth_date}, Current: {current_time}).")
167
  return parsed_data, True
168
  else:
169
- logging.warning(f"Data verification failed. Calculated: {calculated_hash}, Received: {received_hash}")
170
  return parsed_data, False
171
  except Exception as e:
172
- logging.error(f"Error verifying Telegram data: {e}")
173
  return None, False
174
 
175
  TEMPLATE = """
@@ -589,7 +571,6 @@ TEMPLATE = """
589
 
590
  function setupTelegram() {
591
  if (!tg || !tg.initData) {
592
- console.error("Telegram WebApp script not loaded or initData is missing.");
593
  const greetingElement = document.getElementById('greeting');
594
  if(greetingElement) greetingElement.textContent = 'Не удалось связаться с Telegram.';
595
  document.body.style.visibility = 'visible';
@@ -616,13 +597,13 @@ TEMPLATE = """
616
  })
617
  .then(data => {
618
  if (data.status === 'ok' && data.verified) {
619
- console.log('Backend verification successful.');
620
  } else {
621
- console.warn('Backend verification failed:', data.message);
622
  }
623
  })
624
  .catch(error => {
625
- console.error('Error sending initData for verification:', error);
626
  });
627
 
628
  const user = tg.initDataUnsafe?.user;
@@ -632,7 +613,7 @@ TEMPLATE = """
632
  greetingElement.textContent = `Добро пожаловать, ${name}! 👋`;
633
  } else {
634
  greetingElement.textContent = 'Добро пожаловать!';
635
- console.warn('Telegram User data not available (initDataUnsafe.user is empty).');
636
  }
637
 
638
  const contactButtons = document.querySelectorAll('.contact-link');
@@ -666,7 +647,7 @@ TEMPLATE = """
666
  }
667
  });
668
  } else {
669
- console.error("Modal elements not found!");
670
  }
671
 
672
  document.body.style.visibility = 'visible';
@@ -675,11 +656,10 @@ TEMPLATE = """
675
  if (window.Telegram && window.Telegram.WebApp) {
676
  setupTelegram();
677
  } else {
678
- console.warn("Telegram WebApp script not immediately available, waiting for window.onload");
679
  window.addEventListener('load', setupTelegram);
680
  setTimeout(() => {
681
  if (document.body.style.visibility !== 'visible') {
682
- console.error("Telegram WebApp script fallback timeout triggered.");
683
  const greetingElement = document.getElementById('greeting');
684
  if(greetingElement) greetingElement.textContent = 'Ошибка загрузки интерфейса Telegram.';
685
  document.body.style.visibility = 'visible';
@@ -881,7 +861,7 @@ ADMIN_TEMPLATE = """
881
  } catch (error) {
882
  statusMessage.textContent = `Ошибка ${action}: ${error.message}`;
883
  statusMessage.style.color = 'var(--admin-danger)';
884
- console.error(`Error during ${action}:`, error);
885
  } finally {
886
  loader.style.display = 'none';
887
  }
@@ -904,7 +884,6 @@ dp = Dispatcher()
904
 
905
  def generate_bot_response(query: str, context: str):
906
  if not GEMINI_API_KEY:
907
- logging.warning("GEMINI_API_KEY not set. Cannot use AI.")
908
  return "Извините, функция ответа с использованием AI временно недоступна."
909
 
910
  lower_query = query.lower()
@@ -928,14 +907,14 @@ USER QUERY: {query}
928
  ASSISTANT RESPONSE:"""
929
 
930
  contents = [
931
- types.Content(
932
  role="user",
933
  parts=[
934
- types.Part.from_text(text=prompt),
935
  ],
936
  ),
937
  ]
938
- generate_content_config = types.GenerateContentConfig(
939
  response_mime_type="text/plain",
940
  temperature=0.1,
941
  max_output_tokens=500
@@ -949,7 +928,6 @@ ASSISTANT RESPONSE:"""
949
  return response.text.strip()
950
 
951
  except Exception as e:
952
- logging.error(f"Error generating AI response: {e}")
953
  return "Извините, произошла ошибка при обработке вашего запроса."
954
 
955
  @dp.message()
@@ -987,7 +965,6 @@ def verify_data():
987
  user_json_str = unquote(user_data_parsed['user'][0])
988
  user_info_dict = json.loads(user_json_str)
989
  except Exception as e:
990
- logging.error(f"Could not parse user JSON: {e}")
991
  user_info_dict = {}
992
 
993
  if is_valid:
@@ -1011,11 +988,9 @@ def verify_data():
1011
  save_visitor_data(user_entry)
1012
  return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200
1013
  else:
1014
- logging.warning(f"Verification failed for user: {user_info_dict.get('id')}")
1015
  return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403
1016
 
1017
  except Exception as e:
1018
- logging.exception("Error in /verify endpoint")
1019
  return jsonify({"status": "error", "message": "Internal server error"}), 500
1020
 
1021
  @app.route('/admin')
@@ -1043,54 +1018,17 @@ def start_bot_polling():
1043
  try:
1044
  asyncio.run(dp.start_polling(bot))
1045
  except Exception as e:
1046
- logging.error(f"Error in bot polling thread: {e}")
1047
 
1048
  if __name__ == '__main__':
1049
- print("---")
1050
- print("--- MORSHEN GROUP SERVER (FLASK + AIOGRAM) ---")
1051
- print("---")
1052
- print(f"Flask server starting on http://{HOST}:{PORT}")
1053
- print(f"Using Bot Token ID: {BOT_TOKEN.split(':')[0]}")
1054
- print(f"Visitor data file: {DATA_FILE}")
1055
- print(f"Hugging Face Repo: {REPO_ID}")
1056
- print(f"HF Data Path: {HF_DATA_FILE_PATH}")
1057
- if not HF_TOKEN_READ or not HF_TOKEN_WRITE:
1058
- print("---")
1059
- print("--- WARNING: HUGGING FACE TOKEN(S) NOT SET ---")
1060
- print("--- Backup/restore functionality will be limited. Set HF_TOKEN_READ and HF_TOKEN_WRITE environment variables.")
1061
- print("---")
1062
- else:
1063
- print("--- Hugging Face tokens found.")
1064
- print("--- Attempting initial data download from Hugging Face...")
1065
- download_data_from_hf()
1066
-
1067
- if not GEMINI_API_KEY:
1068
- print("---")
1069
- print("--- WARNING: GEMINI_API_KEY NOT SET ---")
1070
- print("--- AI response functionality will be limited or unavailable. Set GEMINI_API_KEY environment variable.")
1071
- print("---")
1072
- else:
1073
- print("--- GEMINI_API_KEY found.")
1074
- print(f"--- Using AI model: {GENAI_MODEL}")
1075
-
1076
  load_visitor_data()
1077
 
1078
- print("---")
1079
- print("--- SECURITY WARNING ---")
1080
- print("--- The /admin route and its sub-routes are NOT protected.")
1081
- print("--- Implement proper authentication before deploying.")
1082
- print("---")
1083
-
1084
  if HF_TOKEN_WRITE:
1085
  backup_thread = threading.Thread(target=periodic_backup, daemon=True)
1086
  backup_thread.start()
1087
- print("--- Periodic backup thread started (every hour).")
1088
- else:
1089
- print("--- Periodic backup disabled (HF_TOKEN_WRITE missing).")
1090
 
1091
  bot_thread = threading.Thread(target=start_bot_polling, daemon=True)
1092
  bot_thread.start()
1093
- print("--- Telegram bot polling thread started.")
1094
 
1095
- print("--- Server Ready ---")
1096
  app.run(host=HOST, port=PORT, debug=False)
 
17
 
18
  from aiogram import Bot, Dispatcher, types, F
19
  from google import genai
20
+ from google.genai import types as genai_types
21
 
22
  BOT_TOKEN = os.getenv("BOT_TOKEN", "7566834146:AAGiG4MaTZZvvtVsqEJVG5SYK5hUlc_Ewo")
23
  HOST = '0.0.0.0'
 
41
  def download_data_from_hf():
42
  global visitor_data_cache
43
  if not HF_TOKEN_READ:
 
44
  return False
45
  try:
 
46
  hf_hub_download(
47
  repo_id=REPO_ID,
48
  filename=HF_DATA_FILE_PATH,
 
53
  force_download=True,
54
  etag_timeout=10
55
  )
 
56
  with _data_lock:
57
  try:
58
  with open(DATA_FILE, 'r', encoding='utf-8') as f:
59
  visitor_data_cache = json.load(f)
 
60
  except (FileNotFoundError, json.JSONDecodeError) as e:
 
61
  visitor_data_cache = {}
62
  return True
63
  except RepositoryNotFoundError:
64
+ pass
65
  except Exception as e:
66
+ pass
67
  return False
68
 
69
  def load_visitor_data():
 
73
  try:
74
  with open(DATA_FILE, 'r', encoding='utf-8') as f:
75
  visitor_data_cache = json.load(f)
 
76
  except FileNotFoundError:
 
77
  visitor_data_cache = {}
78
  except json.JSONDecodeError:
 
79
  visitor_data_cache = {}
80
  except Exception as e:
 
81
  visitor_data_cache = {}
82
  return visitor_data_cache
83
 
 
87
  visitor_data_cache.update(data)
88
  with open(DATA_FILE, 'w', encoding='utf-8') as f:
89
  json.dump(visitor_data_cache, f, ensure_ascii=False, indent=4)
 
90
  upload_data_to_hf_async()
91
  except Exception as e:
92
+ pass
93
 
94
  def upload_data_to_hf():
95
  if not HF_TOKEN_WRITE:
 
96
  return
97
  if not os.path.exists(DATA_FILE):
 
98
  return
99
 
100
  try:
 
102
  with _data_lock:
103
  file_content_exists = os.path.getsize(DATA_FILE) > 0
104
  if not file_content_exists:
 
105
  return
106
 
 
107
  api.upload_file(
108
  path_or_fileobj=DATA_FILE,
109
  path_in_repo=HF_DATA_FILE_PATH,
 
112
  token=HF_TOKEN_WRITE,
113
  commit_message=f"Update visitor data {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
114
  )
 
115
  except Exception as e:
116
+ pass
117
 
118
  def upload_data_to_hf_async():
119
  upload_thread = threading.Thread(target=upload_data_to_hf, daemon=True)
 
121
 
122
  def periodic_backup():
123
  if not HF_TOKEN_WRITE:
 
124
  return
125
  while True:
126
  time.sleep(3600)
 
127
  upload_data_to_hf()
128
 
129
  def verify_telegram_data(init_data_str):
 
146
  auth_date = int(parsed_data.get('auth_date', [0])[0])
147
  current_time = int(time.time())
148
  if current_time - auth_date > 86400:
149
+ pass
150
  return parsed_data, True
151
  else:
152
+ pass
153
  return parsed_data, False
154
  except Exception as e:
 
155
  return None, False
156
 
157
  TEMPLATE = """
 
571
 
572
  function setupTelegram() {
573
  if (!tg || !tg.initData) {
 
574
  const greetingElement = document.getElementById('greeting');
575
  if(greetingElement) greetingElement.textContent = 'Не удалось связаться с Telegram.';
576
  document.body.style.visibility = 'visible';
 
597
  })
598
  .then(data => {
599
  if (data.status === 'ok' && data.verified) {
600
+
601
  } else {
602
+
603
  }
604
  })
605
  .catch(error => {
606
+
607
  });
608
 
609
  const user = tg.initDataUnsafe?.user;
 
613
  greetingElement.textContent = `Добро пожаловать, ${name}! 👋`;
614
  } else {
615
  greetingElement.textContent = 'Добро пожаловать!';
616
+
617
  }
618
 
619
  const contactButtons = document.querySelectorAll('.contact-link');
 
647
  }
648
  });
649
  } else {
650
+
651
  }
652
 
653
  document.body.style.visibility = 'visible';
 
656
  if (window.Telegram && window.Telegram.WebApp) {
657
  setupTelegram();
658
  } else {
659
+
660
  window.addEventListener('load', setupTelegram);
661
  setTimeout(() => {
662
  if (document.body.style.visibility !== 'visible') {
 
663
  const greetingElement = document.getElementById('greeting');
664
  if(greetingElement) greetingElement.textContent = 'Ошибка загрузки интерфейса Telegram.';
665
  document.body.style.visibility = 'visible';
 
861
  } catch (error) {
862
  statusMessage.textContent = `Ошибка ${action}: ${error.message}`;
863
  statusMessage.style.color = 'var(--admin-danger)';
864
+
865
  } finally {
866
  loader.style.display = 'none';
867
  }
 
884
 
885
  def generate_bot_response(query: str, context: str):
886
  if not GEMINI_API_KEY:
 
887
  return "Извините, функция ответа с использованием AI временно недоступна."
888
 
889
  lower_query = query.lower()
 
907
  ASSISTANT RESPONSE:"""
908
 
909
  contents = [
910
+ genai_types.Content(
911
  role="user",
912
  parts=[
913
+ genai_types.Part.from_text(text=prompt),
914
  ],
915
  ),
916
  ]
917
+ generate_content_config = genai_types.GenerateContentConfig(
918
  response_mime_type="text/plain",
919
  temperature=0.1,
920
  max_output_tokens=500
 
928
  return response.text.strip()
929
 
930
  except Exception as e:
 
931
  return "Извините, произошла ошибка при обработке вашего запроса."
932
 
933
  @dp.message()
 
965
  user_json_str = unquote(user_data_parsed['user'][0])
966
  user_info_dict = json.loads(user_json_str)
967
  except Exception as e:
 
968
  user_info_dict = {}
969
 
970
  if is_valid:
 
988
  save_visitor_data(user_entry)
989
  return jsonify({"status": "ok", "verified": True, "user": user_info_dict}), 200
990
  else:
 
991
  return jsonify({"status": "error", "verified": False, "message": "Invalid data"}), 403
992
 
993
  except Exception as e:
 
994
  return jsonify({"status": "error", "message": "Internal server error"}), 500
995
 
996
  @app.route('/admin')
 
1018
  try:
1019
  asyncio.run(dp.start_polling(bot))
1020
  except Exception as e:
1021
+ pass
1022
 
1023
  if __name__ == '__main__':
1024
+ download_data_from_hf()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1025
  load_visitor_data()
1026
 
 
 
 
 
 
 
1027
  if HF_TOKEN_WRITE:
1028
  backup_thread = threading.Thread(target=periodic_backup, daemon=True)
1029
  backup_thread.start()
 
 
 
1030
 
1031
  bot_thread = threading.Thread(target=start_bot_polling, daemon=True)
1032
  bot_thread.start()
 
1033
 
 
1034
  app.run(host=HOST, port=PORT, debug=False)