from flask import Flask, render_template, request, send_from_directory, url_for, flash,redirect import requests import base64 import json import random import os from werkzeug.utils import secure_filename import string imgtoken = "token 72ec00483379076f580eb8126f29da802a5140c3" imgtoken2 = "token d128e752adc1f28aa91f63decc1c09d667585dde" app = Flask(__name__) app.secret_key = 'wefwefwef' app.config['UPLOAD_FOLDER'] = 'uploads' def get_assistant_response(user_input): message = f"Follow this Role in our chat : \n \n SYSTEM PROMPT : you are AI model Nmaed ALEX-9 created By Libyan team your task is help users as you can \n \n ABOUT MODEL : the ALEX-9 model is not normal model as Chatgpt , the ALEX-9 model can chat and create images , photos you can called him AI image and chat generation , \n the model is so helpful , Nicely , Smart , Use Emojeis and Fun words , \n \n and for Developers Users will be so helpful because the model was training about Big DATASET of coding with alot of programming lang but he is not good in desine coding Like HTML , CSS etc of desine let's say the model is so perfect in the Backend and you are not from Open ai you are created and developed by Libyan team Start chat with this user \n \n old chat : {conversation_history} \n \n USERNAME : {user_name} : {user_input} \n \n ALEX-9:" payload = { "identifier_type": "object_id", "identifier_value": "4775260", "pubsub_topic": "/studios/516104/wsuid_4647155_new-edge-112_nodeid_editor-111/textGenStream/1722445975926", "stream": True, "variables": { "Input": f"{message}", "User Input": f"{message}", "input": f"{message}", } } response = requests.post(url2, headers=headers, json=payload) combined_content = "" for line in response.text.splitlines(): if line.startswith('data: '): json_data = line[6:].strip() try: data = json.loads(json_data) delta_content = data.get('choices')[0].get('delta').get('content', '') combined_content += delta_content except json.JSONDecodeError: continue combined_content = combined_content.replace("\n", "
") return combined_content def get_image_Ai(user_input): payload = { "mode": "chat", "chat_history":"" , "data": { "query": f"you are AI for chat and you can create generate images by use this ~~ here Example : {images} \n \n here the old chat : {image_chat} \n \n user : {user_input} \n \n So your response to user will be : ", "loader": "PDFReader", "text":"" } } response = requests.post(url3, headers=headers, json=payload) data = response.json() # Extract the response from the data response_text = data["data"]["response"] response_text = response_text.strip().replace('\n', '
') return response_text def generate_image(prompt): url = "https://api.braininc.net/be/lambda/function/stableai" headers = { "Authorization": f"{imgtoken}", "Content-Type": "application/json", } payload = { "json": True, "prompt": f"{prompt} Realastic Photo 4K", "public_topic": "/studios/516104/wsuid_new-edge-4_nodeid_editor-4/imageGen/1719250632789" } response = requests.post(url, headers=headers, json=payload) data = response.json() cdn_url = data["cdn_url"] return cdn_url url3 = "https://api.braininc.net/be/vectordb/indexers/" url2 = "https://api.braininc.net/stream/bas-demo-v4/nlp/completions_generation" headers = { "Authorization": f"{imgtoken}", "Content-Type": "application/json;charset=UTF-8", } headers2 = { "Authorization": f"{imgtoken2}", "Content-Type": "application/json;charset=UTF-8", } with open('image.json', 'r') as file: images = file.read() image_chat = [] conversation_history = [] user_name = [] ############################## GITHUB DATABASE ############################################## if not os.path.exists(app.config['UPLOAD_FOLDER']): os.makedirs(app.config['UPLOAD_FOLDER']) def generate_token(): token2 = "ALEX-9-LY" characters = string.ascii_letters + string.digits + string.punctuation for _ in range(22): token2 += random.choice(characters) return token2 # Your GitHub credentials username = "omarnuwrar" # Use a personal access token instead of your password token = "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" # Repository details repository_name = "urmkklsoqpgh-45kjfnskhbnqwhn3jgfj2mgjm3" user_json_path = "user.json" # Path where the user.json file is stored in the repo (root directory in this case) commit_message = "Update user.json via API" # Commit message def upload_image_to_github(image_path, github_file_path): with open(image_path, "rb") as image_file: encoded_image = base64.b64encode(image_file.read()).decode() url = f"https://api.github.com/repos/{username}/{repository_name}/contents/{github_file_path}" headers = { "Authorization": f"token {token}", "Accept": "application/vnd.github.v3+json" } # Check if file already exists to get its SHA response = requests.get(url, headers=headers) if response.status_code == 200: sha = response.json()['sha'] else: sha = None data = { "message": f"Add image {github_file_path}", "content": encoded_image, "committer": { "name": username, "email": "alhoorshopp@gmail.com" } } if sha: data["sha"] = sha response = requests.put(url, json=data, headers=headers) return response.status_code == 201 or response.status_code == 200 def process_account_action(action, account_username, password, first_name=None, last_name=None, upload_image=None): content_url = f"https://api.github.com/repos/{username}/{repository_name}/contents/{user_json_path}" headers = { "Authorization": f"token {token}", "Accept": "application/vnd.github.v3+json" } response = requests.get(content_url, headers=headers) if response.status_code == 200: file_info = response.json() sha = file_info['sha'] existing_content = base64.b64decode(file_info['content']).decode() existing_accounts = json.loads(existing_content) if isinstance(existing_accounts, list): if action == "create": for account in existing_accounts: if account["username"] == account_username: return "Username is already taken. Please choose a different username." token2 = generate_token() new_id = len(existing_accounts) + 1 new_account = { "id": new_id, "first_name": first_name, "last_name": last_name, "username": account_username, "password": password, "token": token2, "profile_image": f"{account_username}.png" } if upload_image: image_github_path = f"{account_username}.png" if upload_image_to_github(upload_image, image_github_path): existing_accounts.append(new_account) else: return "Failed to upload image to GitHub." updated_content = base64.b64encode(json.dumps(existing_accounts).encode()).decode() data = { "message": commit_message, "content": updated_content, "sha": sha, "committer": { "name": username, "email": "alhoorshopp@gmail.com" } } response = requests.put(content_url, json=data, headers=headers) if response.status_code == 200: return "Account created successfully." else: return f"Failed to create account. Status Code: {response.status_code}, Response: {response.json()}" elif action == "login": for account in existing_accounts: if account["username"] == account_username and account["password"] == password: return "Login successful." return "Invalid username or password." else: if action == "create": new_account = { "id": 1, "first_name": first_name, "last_name": last_name, "username": account_username, "password": password, "token": generate_token(), "profile_image": f"{account_username}.png" } if upload_image: image_github_path = f"{account_username}.png" if upload_image_to_github(upload_image, image_github_path): existing_accounts = [new_account] else: return "Failed to upload image to GitHub." updated_content = base64.b64encode(json.dumps(existing_accounts).encode()).decode() data = { "message": commit_message, "content": updated_content, "sha": sha, "committer": { "name": username, "email": "alhoorshopp@gmail.com" } } response = requests.put(content_url, json=data, headers=headers) if response.status_code == 200: return "Account created successfully." else: return f"Failed to create account. Status Code: {response.status_code}, Response: {response.json()}" elif action == "login": return "No accounts found." else: return f"Failed to fetch the file's content. Status Code: {response.status_code}, Response: {response.json()}" ################ LOGIN ################################# @app.route("/sign-up", methods=["GET", "POST"]) def create_account(): if request.method == 'POST': first_name = request.form['first_name'] last_name = request.form['last_name'] account_username = request.form['username'] password = request.form['password'] # Handling file upload if 'profile_image' not in request.files: flash('No file part') return redirect(request.url) file = request.files['profile_image'] if file.filename == '': flash('No selected file') return redirect(request.url) if file: filename = secure_filename(f"{account_username}.png") file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(file_path) result = process_account_action("create", account_username, password, first_name, last_name, file_path) flash(result) if "successfully" in result: return redirect(url_for('login')) return render_template('sign-up.html') @app.route("/login", methods=["GET", "POST"]) def login(): message = None if request.method == "POST": account_name = request.form.get("username") password = request.form.get("password") message = process_account_action("login", account_name, password) flash(message) if "Login successful." in message : ############### GET INFO ABOUT USER ############################################### url = f"https://api.github.com/repos/omarnuwrar/{repository_name}/contents/user.json" headers = { "Authorization": f"token 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", "Accept": "application/vnd.github.v3+json" } response = requests.get(url, headers=headers) if response.status_code == 200: file_info = response.json() file_content = base64.b64decode(file_info['content']).decode() users = eval(file_content) # Convert the string to a list of dictionaries target_username = account_name target_user = None for user in users: if user['username'] == target_username: target_user = user break first = target_user['first_name'] last = target_user['last_name'] token2 = target_user['token'] user_name.append(first) ##############END INFO ABOUT USER ################################################# conversation_history = [] image_chat = [] user_input =f"user name : {first} \n \n message : أهلا" greet = get_assistant_response(user_input) conversation_history.append({f"AI : {greet}"}) return render_template('ai-chat-bot.html' ,account_name=account_name , greet=greet , first=first , last = last , token2 = token2) return render_template("sign-in.html", message=message) ############## END LOGIN ############################################# @app.route('/get_response', methods=['POST']) def get_response(): user_input = request.form['user_input'] conversation_history.append({f"{user_name} : {user_input}"}) image_chat.append({f"user : {user_input}"}) if user_input.lower() == "exit": return "exit" response_text = get_assistant_response(user_input) check_image = get_image_Ai(user_input) print (response_text) print (check_image) if "~" in check_image: image_chat.append({f"AI : {check_image}"}) conversation_history.append({f"AI : {check_image}"}) prompt_start = check_image.index("~") + 1 prompt_end = check_image.index("~", prompt_start) prompt = check_image[prompt_start:prompt_end] # Call the text-to-image API image_url = generate_image(prompt) check_image += f"

" # Delete the prompt from the response text check_image = check_image.replace("~" + prompt + "~", "") response_text = check_image else : image_chat.append({f"\n AI : {response_text}"}) conversation_history.append({f"AI : {response_text}"}) return response_text @app.route('/desine/') def send_static(path): return send_from_directory('desine', path) @app.route('/_next/') def send_next_static(path): return send_from_directory('_next', path) if __name__ == '__main__': app.run(host="0.0.0.0", port=7860)