Spaces:
Sleeping
Sleeping
| import os | |
| import schedule | |
| import time | |
| import random | |
| import requests | |
| import re | |
| import base64 | |
| import urllib3 | |
| from flask import Flask | |
| from threading import Thread | |
| from PIL import Image, ImageDraw | |
| urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) | |
| # ====================================================== | |
| # 🔐 KEY SETUP | |
| # ====================================================== | |
| FB_TOKEN = os.environ.get("FB_TOKEN") | |
| TEXT_API_KEY = os.environ.get("TEXT_API_KEY") | |
| IMAGE_API_KEY = os.environ.get("IMAGE_API_KEY") | |
| HF_TOKEN = os.environ.get("HF_TOKEN") # Hugging Face ടോക്കൺ വേരിയബിളിൽ ചേർക്കുക | |
| app = Flask(__name__) | |
| def home(): | |
| return "Ziya V105 (Hybrid Engine) is Running!" | |
| # Config | |
| HISTORY_FILE = "posted_ideas.txt" | |
| IMAGE_DIR = "generated_images" | |
| os.makedirs(IMAGE_DIR, exist_ok=True) | |
| OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions" | |
| def clean_text(text): | |
| if not text: return "" | |
| text = re.sub(r'^(Sure|Okay|Here is|Translation|Translate|Certainly|Final Post|Here\'s the translation).*?:', '', text, flags=re.IGNORECASE | re.DOTALL) | |
| text = re.sub(r'<[^>]*>', '', text) | |
| text = text.replace("**", "").replace("__", "").replace("`", "") | |
| return text.strip() | |
| def post_to_facebook(caption, image_path=None): | |
| url = f"https://graph.facebook.com/me/{'photos' if image_path else 'feed'}" | |
| params = {'access_token': FB_TOKEN} | |
| try: | |
| if image_path: | |
| with open(image_path, 'rb') as img: | |
| res = requests.post(url, params=params, data={'caption': caption}, files={'source': img}, timeout=120) | |
| else: | |
| res = requests.post(url, params=params, data={'message': caption}, timeout=120) | |
| return res.status_code == 200 | |
| except: return False | |
| # ⚡ Hugging Face Inference API for Fast Topic Selection | |
| def call_hf_api(prompt): | |
| if not HF_TOKEN: return None | |
| API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2" | |
| headers = {"Authorization": f"Bearer {HF_TOKEN}"} | |
| try: | |
| response = requests.post(API_URL, headers=headers, json={"inputs": prompt}, timeout=30) | |
| result = response.json() | |
| if isinstance(result, list): return result[0]['generated_text'] | |
| return None | |
| except: return None | |
| def call_ai_text(prompt, temp=0.7): | |
| headers = {"Authorization": f"Bearer {TEXT_API_KEY}", "Content-Type": "application/json"} | |
| payload = { | |
| "model": "google/gemini-2.0-flash-lite-preview-02-05:free", | |
| "messages": [{"role": "user", "content": prompt}], | |
| "temperature": temp | |
| } | |
| try: | |
| res = requests.post(OPENROUTER_URL, headers=headers, json=payload, timeout=60) | |
| return res.json()['choices'][0]['message']['content'] | |
| except: return None | |
| def call_ai_image(prompt): | |
| headers = {"Authorization": f"Bearer {IMAGE_API_KEY}", "Content-Type": "application/json"} | |
| payload = {"model": "google/gemini-2.5-flash-image", "messages": [{"role": "user", "content": prompt}], "modalities": ["image"]} | |
| try: | |
| res = requests.post(OPENROUTER_URL, headers=headers, json=payload, timeout=90) | |
| b64 = res.json()['choices'][0]['message']['images'][0]['image_url']['url'].split(",")[1] | |
| path = os.path.join(IMAGE_DIR, f"gen_{int(time.time())}.png") | |
| with open(path, "wb") as f: f.write(base64.b64decode(b64)) | |
| return path | |
| except: return None | |
| def process_and_post(): | |
| print("\n⚡ Starting V105 Hybrid Engine Cycle...") | |
| # 1. Topic (HF API for Speed) | |
| print("🔍 Finding Topic via HF...") | |
| topic_data = call_hf_api("Suggest one unique Kerala historical place. Output only name.") | |
| topic = clean_text(topic_data) if topic_data else random.choice(["Muziris", "Bekal Fort", "Edakkal Caves"]) | |
| print(f"🎯 Selected: {topic}") | |
| # 2. Content (OpenRouter for Quality Malayalam) | |
| print(f"✍️ Generating Malayalam Content for: {topic}") | |
| mal_content = call_ai_text(f"Write 5 sentences in Malayalam about {topic}. No English. Add a quiz question.") | |
| if not mal_content: return | |
| caption = clean_text(mal_content) | |
| # 3. Image | |
| print("🎨 Generating Image...") | |
| image_path = call_ai_image(f"Cinematic photorealistic view of {topic}, Kerala.") | |
| # 4. Post | |
| print("📤 Publishing to Facebook...") | |
| if post_to_facebook(caption, image_path): | |
| print(f"✅ V105 Success: {topic}") | |
| if image_path: os.remove(image_path) | |
| else: | |
| print("🚨 Posting Failed. Check Token/Permissions.") | |
| def run_schedule(): | |
| while True: | |
| schedule.run_pending() | |
| time.sleep(60) | |
| if __name__ == "__main__": | |
| t = Thread(target=run_schedule) | |
| t.daemon = True | |
| t.start() | |
| # Immediate Run | |
| process_and_post() | |
| schedule.every().day.at("09:00").do(process_and_post) | |
| schedule.every().day.at("19:30").do(process_and_post) | |
| app.run(host='0.0.0.0', port=7860) | |