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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import threading
|
| 5 |
+
import requests
|
| 6 |
+
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 (Load Secrets) ---
|
| 15 |
+
app = Flask(__name__)
|
| 16 |
+
|
| 17 |
+
# 1. Setup Firebase
|
| 18 |
+
cred_json = json.loads(os.environ.get('FIREBASE_CREDENTIALS'))
|
| 19 |
+
cred = credentials.Certificate(cred_json)
|
| 20 |
+
firebase_admin.initialize_app(cred)
|
| 21 |
+
db = firestore.client()
|
| 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 Keys (Rotation)
|
| 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}
|
| 46 |
+
data = {'chat_id': CHANNEL_ID, 'caption': caption}
|
| 47 |
+
response = requests.post(url, files=files, data=data)
|
| 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: # Wrap text
|
| 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 (The Automation Engine) ---
|
| 84 |
+
def worker_loop():
|
| 85 |
+
print("Worker started...")
|
| 86 |
+
topics = ["Newton Laws", "Python Basics", "Photosynthesis", "World War 2", "Algebra", "Cyber Security"] # Add more via logic later
|
| 87 |
+
|
| 88 |
+
while True:
|
| 89 |
+
try:
|
| 90 |
+
# 1. Pick a Topic
|
| 91 |
+
topic = random.choice(topics)
|
| 92 |
+
print(f"Generating notes for: {topic}")
|
| 93 |
+
|
| 94 |
+
# 2. Generate Content
|
| 95 |
+
model = get_gemini_model()
|
| 96 |
+
response = model.generate_content(f"Write detailed educational notes on {topic}. Use headings and bullet points.")
|
| 97 |
+
content = response.text
|
| 98 |
+
|
| 99 |
+
# 3. Create PDF
|
| 100 |
+
pdf_name = f"{topic.replace(' ', '_')}.pdf"
|
| 101 |
+
create_pdf(content, pdf_name)
|
| 102 |
+
|
| 103 |
+
# 4. Upload to Telegram
|
| 104 |
+
link = upload_to_telegram(pdf_name, f"Notes for {topic}")
|
| 105 |
+
|
| 106 |
+
if link:
|
| 107 |
+
# 5. Save to Firebase
|
| 108 |
+
doc_ref = db.collection('notes').add({
|
| 109 |
+
'title': topic,
|
| 110 |
+
'subject': 'General',
|
| 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"Error in worker: {e}")
|
| 126 |
+
time.sleep(60)
|
| 127 |
+
|
| 128 |
+
# Start Worker in Background
|
| 129 |
+
threading.Thread(target=worker_loop, daemon=True).start()
|
| 130 |
+
|
| 131 |
+
# --- WEB SERVER (For Uptime & User Uploads) ---
|
| 132 |
+
|
| 133 |
+
@app.route('/')
|
| 134 |
+
def home():
|
| 135 |
+
return "System Operational. Worker is running."
|
| 136 |
+
|
| 137 |
+
@app.route('/upload', methods=['POST'])
|
| 138 |
+
def upload_note():
|
| 139 |
+
"""Receives file from Website -> Sends to Telegram -> Saves to Firebase"""
|
| 140 |
+
if 'file' not in request.files:
|
| 141 |
+
return jsonify({'error': 'No file part'}), 400
|
| 142 |
+
|
| 143 |
+
file = request.files['file']
|
| 144 |
+
title = request.form.get('title')
|
| 145 |
+
subject = request.form.get('subject')
|
| 146 |
+
uploader = request.form.get('uploaderName', 'Anonymous')
|
| 147 |
+
|
| 148 |
+
if file:
|
| 149 |
+
# Save temporarily
|
| 150 |
+
filename = file.filename
|
| 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 |
+
os.remove(filename) # Cleanup
|
| 167 |
+
return jsonify({'success': True, 'link': link}), 200
|
| 168 |
+
|
| 169 |
+
return jsonify({'error': 'Upload failed'}), 500
|
| 170 |
+
|
| 171 |
+
if __name__ == '__main__':
|
| 172 |
+
app.run(host='0.0.0.0', port=7860)
|