Spaces:
Sleeping
Sleeping
Bahawal Ali commited on
Update main.py
Browse files
main.py
CHANGED
|
@@ -7,39 +7,43 @@ import random
|
|
| 7 |
import firebase_admin
|
| 8 |
from firebase_admin import credentials, firestore
|
| 9 |
from flask import Flask, request, jsonify
|
|
|
|
| 10 |
from reportlab.pdfgen import canvas
|
| 11 |
from reportlab.lib.pagesizes import letter
|
| 12 |
import google.generativeai as genai
|
| 13 |
|
| 14 |
-
# --- CONFIGURATION
|
| 15 |
app = Flask(__name__)
|
|
|
|
| 16 |
|
| 17 |
# 1. Setup Firebase
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
# 2. Setup Telegram
|
| 24 |
BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')
|
| 25 |
CHANNEL_ID = os.environ.get('TELEGRAM_CHANNEL_ID')
|
| 26 |
|
| 27 |
-
# 3. Setup Gemini
|
| 28 |
-
API_KEYS = os.environ.get('GEMINI_API_KEYS').split(',')
|
| 29 |
current_key_index = 0
|
| 30 |
|
| 31 |
def get_gemini_model():
|
| 32 |
global current_key_index
|
|
|
|
| 33 |
key = API_KEYS[current_key_index]
|
| 34 |
-
# Rotate Key for next time
|
| 35 |
current_key_index = (current_key_index + 1) % len(API_KEYS)
|
| 36 |
genai.configure(api_key=key)
|
| 37 |
return genai.GenerativeModel('gemini-pro')
|
| 38 |
|
| 39 |
# --- HELPER FUNCTIONS ---
|
| 40 |
-
|
| 41 |
def upload_to_telegram(file_path, caption):
|
| 42 |
-
"""Uploads a file to Telegram and returns the Direct Link logic"""
|
| 43 |
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendDocument"
|
| 44 |
with open(file_path, 'rb') as f:
|
| 45 |
files = {'document': f}
|
|
@@ -48,125 +52,109 @@ def upload_to_telegram(file_path, caption):
|
|
| 48 |
|
| 49 |
if response.status_code == 200:
|
| 50 |
msg_id = response.json()['result']['message_id']
|
| 51 |
-
# Telegram Link Format (Change channel username if public)
|
| 52 |
-
# Note: If channel is private, link logic is different. Assuming Public Channel here.
|
| 53 |
channel_username = CHANNEL_ID.replace("@", "")
|
| 54 |
return f"https://t.me/{channel_username}/{msg_id}"
|
| 55 |
return None
|
| 56 |
|
| 57 |
def create_pdf(text, filename):
|
| 58 |
-
"""Converts Text to PDF"""
|
| 59 |
c = canvas.Canvas(filename, pagesize=letter)
|
| 60 |
width, height = letter
|
| 61 |
text_object = c.beginText(40, height - 40)
|
| 62 |
text_object.setFont("Helvetica", 12)
|
| 63 |
-
|
| 64 |
-
# Simple formatting logic
|
| 65 |
lines = text.split('\n')
|
| 66 |
for line in lines:
|
| 67 |
-
if len(line) > 90:
|
| 68 |
parts = [line[i:i+90] for i in range(0, len(line), 90)]
|
| 69 |
for part in parts:
|
| 70 |
text_object.textLine(part)
|
| 71 |
else:
|
| 72 |
text_object.textLine(line)
|
| 73 |
-
|
| 74 |
-
if text_object.getY() < 40: # New Page
|
| 75 |
c.drawText(text_object)
|
| 76 |
c.showPage()
|
| 77 |
text_object = c.beginText(40, height - 40)
|
| 78 |
text_object.setFont("Helvetica", 12)
|
| 79 |
-
|
| 80 |
c.drawText(text_object)
|
| 81 |
c.save()
|
| 82 |
|
| 83 |
-
# --- WORKER THREAD
|
| 84 |
def worker_loop():
|
| 85 |
print("Worker started...")
|
| 86 |
-
topics = ["
|
| 87 |
-
|
| 88 |
while True:
|
| 89 |
try:
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
| 91 |
topic = random.choice(topics)
|
| 92 |
-
print(f"Generating
|
| 93 |
-
|
| 94 |
-
# 2. Generate Content
|
| 95 |
model = get_gemini_model()
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
'downloadUrl': link,
|
| 112 |
-
'uploaderName': 'AI Bot',
|
| 113 |
-
'timestamp': firestore.SERVER_TIMESTAMP
|
| 114 |
-
})
|
| 115 |
-
print(f"Uploaded and Saved: {topic}")
|
| 116 |
-
|
| 117 |
-
# Cleanup
|
| 118 |
-
if os.path.exists(pdf_name):
|
| 119 |
-
os.remove(pdf_name)
|
| 120 |
-
|
| 121 |
-
# Sleep (Important to avoid bans)
|
| 122 |
-
time.sleep(3600) # 1 hour gap between auto-posts
|
| 123 |
|
|
|
|
| 124 |
except Exception as e:
|
| 125 |
-
print(f"
|
| 126 |
time.sleep(60)
|
| 127 |
|
| 128 |
-
# Start Worker
|
| 129 |
threading.Thread(target=worker_loop, daemon=True).start()
|
| 130 |
|
| 131 |
-
# --- WEB SERVER
|
| 132 |
-
|
| 133 |
@app.route('/')
|
| 134 |
def home():
|
| 135 |
-
return "
|
| 136 |
|
| 137 |
@app.route('/upload', methods=['POST'])
|
| 138 |
def upload_note():
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
file.save(filename)
|
| 152 |
-
|
| 153 |
-
# Upload to Telegram
|
| 154 |
-
link = upload_to_telegram(filename, f"User Upload: {title}")
|
| 155 |
-
|
| 156 |
-
# Save to Firebase
|
| 157 |
-
if link:
|
| 158 |
-
db.collection('notes').add({
|
| 159 |
-
'title': title,
|
| 160 |
-
'subject': subject,
|
| 161 |
-
'downloadUrl': link,
|
| 162 |
-
'uploaderName': uploader,
|
| 163 |
-
'timestamp': firestore.SERVER_TIMESTAMP
|
| 164 |
-
})
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
| 168 |
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
if __name__ == '__main__':
|
| 172 |
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 7 |
import firebase_admin
|
| 8 |
from firebase_admin import credentials, firestore
|
| 9 |
from flask import Flask, request, jsonify
|
| 10 |
+
from flask_cors import CORS # <--- YEH ZAROORI HAI
|
| 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) # <--- IJA ZAT DE RAHA HAI WEBSITE KO
|
| 18 |
|
| 19 |
# 1. Setup Firebase
|
| 20 |
+
try:
|
| 21 |
+
cred_env = os.environ.get('FIREBASE_CREDENTIALS')
|
| 22 |
+
cred_json = json.loads(cred_env)
|
| 23 |
+
cred = credentials.Certificate(cred_json)
|
| 24 |
+
firebase_admin.initialize_app(cred)
|
| 25 |
+
db = firestore.client()
|
| 26 |
+
except Exception as e:
|
| 27 |
+
print(f"Firebase Error: {e}")
|
| 28 |
|
| 29 |
# 2. Setup Telegram
|
| 30 |
BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN')
|
| 31 |
CHANNEL_ID = os.environ.get('TELEGRAM_CHANNEL_ID')
|
| 32 |
|
| 33 |
+
# 3. Setup Gemini
|
| 34 |
+
API_KEYS = os.environ.get('GEMINI_API_KEYS', '').split(',')
|
| 35 |
current_key_index = 0
|
| 36 |
|
| 37 |
def get_gemini_model():
|
| 38 |
global current_key_index
|
| 39 |
+
if not API_KEYS or API_KEYS == ['']: return None
|
| 40 |
key = API_KEYS[current_key_index]
|
|
|
|
| 41 |
current_key_index = (current_key_index + 1) % len(API_KEYS)
|
| 42 |
genai.configure(api_key=key)
|
| 43 |
return genai.GenerativeModel('gemini-pro')
|
| 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}
|
|
|
|
| 52 |
|
| 53 |
if response.status_code == 200:
|
| 54 |
msg_id = response.json()['result']['message_id']
|
|
|
|
|
|
|
| 55 |
channel_username = CHANNEL_ID.replace("@", "")
|
| 56 |
return f"https://t.me/{channel_username}/{msg_id}"
|
| 57 |
return None
|
| 58 |
|
| 59 |
def create_pdf(text, filename):
|
|
|
|
| 60 |
c = canvas.Canvas(filename, pagesize=letter)
|
| 61 |
width, height = letter
|
| 62 |
text_object = c.beginText(40, height - 40)
|
| 63 |
text_object.setFont("Helvetica", 12)
|
|
|
|
|
|
|
| 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 |
text_object.textLine(line)
|
| 72 |
+
if text_object.getY() < 40:
|
|
|
|
| 73 |
c.drawText(text_object)
|
| 74 |
c.showPage()
|
| 75 |
text_object = c.beginText(40, height - 40)
|
| 76 |
text_object.setFont("Helvetica", 12)
|
|
|
|
| 77 |
c.drawText(text_object)
|
| 78 |
c.save()
|
| 79 |
|
| 80 |
+
# --- WORKER THREAD ---
|
| 81 |
def worker_loop():
|
| 82 |
print("Worker started...")
|
| 83 |
+
topics = ["Cyber Security", "Python", "Networking", "AI Basics"]
|
|
|
|
| 84 |
while True:
|
| 85 |
try:
|
| 86 |
+
if not API_KEYS or API_KEYS == ['']:
|
| 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 & Secure."
|
| 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
|
| 127 |
+
|
| 128 |
+
file = request.files['file']
|
| 129 |
+
title = request.form.get('title')
|
| 130 |
+
subject = request.form.get('subject')
|
| 131 |
+
uploader = request.form.get('uploaderName', 'Anonymous')
|
| 132 |
|
| 133 |
+
if file:
|
| 134 |
+
filename = f"user_{int(time.time())}_{file.filename}"
|
| 135 |
+
file.save(filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
+
# Upload to Telegram
|
| 138 |
+
link = upload_to_telegram(filename, f"Uploaded by {uploader}: {title}")
|
| 139 |
|
| 140 |
+
# Save to Firebase
|
| 141 |
+
if link:
|
| 142 |
+
db.collection('notes').add({
|
| 143 |
+
'title': title,
|
| 144 |
+
'subject': subject,
|
| 145 |
+
'downloadUrl': link,
|
| 146 |
+
'uploaderName': uploader,
|
| 147 |
+
'timestamp': firestore.SERVER_TIMESTAMP
|
| 148 |
+
})
|
| 149 |
+
os.remove(filename)
|
| 150 |
+
return jsonify({'success': True, 'link': link}), 200
|
| 151 |
+
else:
|
| 152 |
+
return jsonify({'error': 'Telegram Upload Failed'}), 500
|
| 153 |
+
|
| 154 |
+
return jsonify({'error': 'File not found'}), 400
|
| 155 |
+
except Exception as e:
|
| 156 |
+
print(f"Upload Error: {e}")
|
| 157 |
+
return jsonify({'error': str(e)}), 500
|
| 158 |
|
| 159 |
if __name__ == '__main__':
|
| 160 |
app.run(host='0.0.0.0', port=7860)
|