Spaces:
Sleeping
Sleeping
Bahawal Ali commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -7,14 +7,14 @@ import random
|
|
| 7 |
import firebase_admin
|
| 8 |
from firebase_admin import credentials, firestore
|
| 9 |
from flask import Flask, request, jsonify
|
| 10 |
-
from flask_cors import CORS
|
| 11 |
from reportlab.pdfgen import canvas
|
| 12 |
from reportlab.lib.pagesizes import letter
|
| 13 |
import google.generativeai as genai
|
| 14 |
|
| 15 |
# --- CONFIGURATION ---
|
| 16 |
app = Flask(__name__)
|
| 17 |
-
CORS(app)
|
| 18 |
|
| 19 |
# 1. Setup Firebase
|
| 20 |
try:
|
|
@@ -23,8 +23,9 @@ try:
|
|
| 23 |
cred = credentials.Certificate(cred_json)
|
| 24 |
firebase_admin.initialize_app(cred)
|
| 25 |
db = firestore.client()
|
|
|
|
| 26 |
except Exception as e:
|
| 27 |
-
print(f"
|
| 28 |
|
| 29 |
# 2. Setup Telegram
|
| 30 |
BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')
|
|
@@ -44,38 +45,54 @@ def get_gemini_model():
|
|
| 44 |
|
| 45 |
# --- HELPER FUNCTIONS ---
|
| 46 |
def upload_to_telegram(file_path, caption):
|
|
|
|
| 47 |
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendDocument"
|
| 48 |
-
with open(file_path, 'rb') as f:
|
| 49 |
-
files = {'document': f}
|
| 50 |
-
data = {'chat_id': CHANNEL_ID, 'caption': caption}
|
| 51 |
-
response = requests.post(url, files=files, data=data)
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
lines = text.split('\n')
|
| 65 |
-
for line in lines:
|
| 66 |
-
if len(line) > 90:
|
| 67 |
-
parts = [line[i:i+90] for i in range(0, len(line), 90)]
|
| 68 |
-
for part in parts:
|
| 69 |
-
text_object.textLine(part)
|
| 70 |
else:
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
# --- WORKER THREAD ---
|
| 81 |
def worker_loop():
|
|
@@ -83,44 +100,21 @@ def worker_loop():
|
|
| 83 |
topics = ["Cyber Security", "Python", "Networking", "AI Basics"]
|
| 84 |
while True:
|
| 85 |
try:
|
| 86 |
-
|
| 87 |
-
time.sleep(60)
|
| 88 |
-
continue
|
| 89 |
-
|
| 90 |
-
topic = random.choice(topics)
|
| 91 |
-
print(f"Auto-Generating: {topic}")
|
| 92 |
-
model = get_gemini_model()
|
| 93 |
-
if model:
|
| 94 |
-
response = model.generate_content(f"Write educational notes on {topic} in bullet points.")
|
| 95 |
-
if response and response.text:
|
| 96 |
-
pdf_name = f"{topic.replace(' ', '_')}_{int(time.time())}.pdf"
|
| 97 |
-
create_pdf(response.text, pdf_name)
|
| 98 |
-
link = upload_to_telegram(pdf_name, f"Auto-Generated: {topic}")
|
| 99 |
-
if link:
|
| 100 |
-
db.collection('notes').add({
|
| 101 |
-
'title': topic,
|
| 102 |
-
'subject': 'Auto-Generated',
|
| 103 |
-
'downloadUrl': link,
|
| 104 |
-
'uploaderName': 'AI Bot',
|
| 105 |
-
'timestamp': firestore.SERVER_TIMESTAMP
|
| 106 |
-
})
|
| 107 |
-
if os.path.exists(pdf_name): os.remove(pdf_name)
|
| 108 |
-
|
| 109 |
-
time.sleep(3600)
|
| 110 |
except Exception as e:
|
| 111 |
print(f"Worker Error: {e}")
|
| 112 |
time.sleep(60)
|
| 113 |
|
| 114 |
-
# Start Worker
|
| 115 |
threading.Thread(target=worker_loop, daemon=True).start()
|
| 116 |
|
| 117 |
# --- WEB SERVER ROUTES ---
|
| 118 |
@app.route('/')
|
| 119 |
def home():
|
| 120 |
-
return "CyberNotes Backend Online &
|
| 121 |
|
| 122 |
@app.route('/upload', methods=['POST'])
|
| 123 |
def upload_note():
|
|
|
|
| 124 |
try:
|
| 125 |
if 'file' not in request.files:
|
| 126 |
return jsonify({'error': 'No file part'}), 400
|
|
@@ -131,7 +125,9 @@ def upload_note():
|
|
| 131 |
uploader = request.form.get('uploaderName', 'Anonymous')
|
| 132 |
|
| 133 |
if file:
|
| 134 |
-
|
|
|
|
|
|
|
| 135 |
file.save(filename)
|
| 136 |
|
| 137 |
# Upload to Telegram
|
|
@@ -139,6 +135,7 @@ def upload_note():
|
|
| 139 |
|
| 140 |
# Save to Firebase
|
| 141 |
if link:
|
|
|
|
| 142 |
db.collection('notes').add({
|
| 143 |
'title': title,
|
| 144 |
'subject': subject,
|
|
@@ -149,11 +146,17 @@ def upload_note():
|
|
| 149 |
os.remove(filename)
|
| 150 |
return jsonify({'success': True, 'link': link}), 200
|
| 151 |
else:
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
return jsonify({'error': 'File not found'}), 400
|
|
|
|
| 155 |
except Exception as e:
|
| 156 |
-
print(f"
|
|
|
|
|
|
|
| 157 |
return jsonify({'error': str(e)}), 500
|
| 158 |
|
| 159 |
if __name__ == '__main__':
|
|
|
|
| 7 |
import firebase_admin
|
| 8 |
from firebase_admin import credentials, firestore
|
| 9 |
from flask import Flask, request, jsonify
|
| 10 |
+
from flask_cors import CORS
|
| 11 |
from reportlab.pdfgen import canvas
|
| 12 |
from reportlab.lib.pagesizes import letter
|
| 13 |
import google.generativeai as genai
|
| 14 |
|
| 15 |
# --- CONFIGURATION ---
|
| 16 |
app = Flask(__name__)
|
| 17 |
+
CORS(app)
|
| 18 |
|
| 19 |
# 1. Setup Firebase
|
| 20 |
try:
|
|
|
|
| 23 |
cred = credentials.Certificate(cred_json)
|
| 24 |
firebase_admin.initialize_app(cred)
|
| 25 |
db = firestore.client()
|
| 26 |
+
print("DEBUG: Firebase Connected Successfully")
|
| 27 |
except Exception as e:
|
| 28 |
+
print(f"CRITICAL ERROR: Firebase Failed - {e}")
|
| 29 |
|
| 30 |
# 2. Setup Telegram
|
| 31 |
BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')
|
|
|
|
| 45 |
|
| 46 |
# --- HELPER FUNCTIONS ---
|
| 47 |
def upload_to_telegram(file_path, caption):
|
| 48 |
+
print(f"DEBUG: Attempting Telegram Upload... Channel: {CHANNEL_ID}")
|
| 49 |
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendDocument"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
try:
|
| 52 |
+
with open(file_path, 'rb') as f:
|
| 53 |
+
files = {'document': f}
|
| 54 |
+
data = {'chat_id': CHANNEL_ID, 'caption': caption}
|
| 55 |
+
response = requests.post(url, files=files, data=data)
|
| 56 |
+
|
| 57 |
+
# --- DEBUG PRINTING ---
|
| 58 |
+
print(f"DEBUG: Telegram Status Code: {response.status_code}")
|
| 59 |
+
print(f"DEBUG: Telegram Response: {response.text}")
|
| 60 |
+
# ----------------------
|
| 61 |
|
| 62 |
+
if response.status_code == 200:
|
| 63 |
+
msg_id = response.json()['result']['message_id']
|
| 64 |
+
# Remove @ from channel name for link
|
| 65 |
+
clean_channel = CHANNEL_ID.replace("@", "")
|
| 66 |
+
return f"https://t.me/{clean_channel}/{msg_id}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
else:
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
except Exception as e:
|
| 71 |
+
print(f"DEBUG: Telegram Connection Error: {e}")
|
| 72 |
+
return None
|
| 73 |
+
|
| 74 |
+
def create_pdf(text, filename):
|
| 75 |
+
try:
|
| 76 |
+
c = canvas.Canvas(filename, pagesize=letter)
|
| 77 |
+
text_object = c.beginText(40, 750)
|
| 78 |
+
text_object.setFont("Helvetica", 12)
|
| 79 |
+
lines = text.split('\n')
|
| 80 |
+
for line in lines:
|
| 81 |
+
if len(line) > 90:
|
| 82 |
+
parts = [line[i:i+90] for i in range(0, len(line), 90)]
|
| 83 |
+
for part in parts:
|
| 84 |
+
text_object.textLine(part)
|
| 85 |
+
else:
|
| 86 |
+
text_object.textLine(line)
|
| 87 |
+
if text_object.getY() < 40:
|
| 88 |
+
c.drawText(text_object)
|
| 89 |
+
c.showPage()
|
| 90 |
+
text_object = c.beginText(40, 750)
|
| 91 |
+
text_object.setFont("Helvetica", 12)
|
| 92 |
+
c.drawText(text_object)
|
| 93 |
+
c.save()
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"PDF Error: {e}")
|
| 96 |
|
| 97 |
# --- WORKER THREAD ---
|
| 98 |
def worker_loop():
|
|
|
|
| 100 |
topics = ["Cyber Security", "Python", "Networking", "AI Basics"]
|
| 101 |
while True:
|
| 102 |
try:
|
| 103 |
+
time.sleep(3600) # Sleep first to allow server startup
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
except Exception as e:
|
| 105 |
print(f"Worker Error: {e}")
|
| 106 |
time.sleep(60)
|
| 107 |
|
|
|
|
| 108 |
threading.Thread(target=worker_loop, daemon=True).start()
|
| 109 |
|
| 110 |
# --- WEB SERVER ROUTES ---
|
| 111 |
@app.route('/')
|
| 112 |
def home():
|
| 113 |
+
return "CyberNotes Backend Online & Debugging Mode ON."
|
| 114 |
|
| 115 |
@app.route('/upload', methods=['POST'])
|
| 116 |
def upload_note():
|
| 117 |
+
print("DEBUG: Upload Request Received")
|
| 118 |
try:
|
| 119 |
if 'file' not in request.files:
|
| 120 |
return jsonify({'error': 'No file part'}), 400
|
|
|
|
| 125 |
uploader = request.form.get('uploaderName', 'Anonymous')
|
| 126 |
|
| 127 |
if file:
|
| 128 |
+
# Use /tmp folder for safety
|
| 129 |
+
filename = f"/tmp/user_{int(time.time())}_{file.filename}"
|
| 130 |
+
print(f"DEBUG: Saving file to {filename}")
|
| 131 |
file.save(filename)
|
| 132 |
|
| 133 |
# Upload to Telegram
|
|
|
|
| 135 |
|
| 136 |
# Save to Firebase
|
| 137 |
if link:
|
| 138 |
+
print(f"DEBUG: Upload Success! Link: {link}")
|
| 139 |
db.collection('notes').add({
|
| 140 |
'title': title,
|
| 141 |
'subject': subject,
|
|
|
|
| 146 |
os.remove(filename)
|
| 147 |
return jsonify({'success': True, 'link': link}), 200
|
| 148 |
else:
|
| 149 |
+
print("DEBUG: Upload Failed at Telegram Step")
|
| 150 |
+
if os.path.exists(filename): os.remove(filename)
|
| 151 |
+
# Return actual error to frontend (inspect logs for details)
|
| 152 |
+
return jsonify({'error': 'Telegram Upload Failed - Check Server Logs'}), 500
|
| 153 |
|
| 154 |
return jsonify({'error': 'File not found'}), 400
|
| 155 |
+
|
| 156 |
except Exception as e:
|
| 157 |
+
print(f"CRITICAL UPLOAD CRASH: {e}")
|
| 158 |
+
import traceback
|
| 159 |
+
traceback.print_exc()
|
| 160 |
return jsonify({'error': str(e)}), 500
|
| 161 |
|
| 162 |
if __name__ == '__main__':
|