1ae1de6d0d2a87e6834da409bfd891b2 Wanna make your own ai assistant using python for pc?

Wanna make your own ai assistant using python for pc?

 AI, or Artificial Intelligence, refers to computer systems designed to perform tasks that typically require human intelligence—such as learning, reasoning, problem-solving, understanding language, and recognizing patterns or images.

my implemented web app:
                                 touch here              
use search for to google search and late night deepseek api lacks to respond because of free                                                       

1. What is AI?

At its core, AI is about making machines “think” or “act” intelligently. This is achieved through:

  • Machine Learning (ML): Systems learn from data and improve over time.

  • Natural Language Processing (NLP): Understanding and generating human language.

  • Computer Vision: Interpreting and processing images and videos.

  • Robotics: Physical machines with AI control for tasks.

  • Expert Systems: Knowledge-based reasoning.


2. Importance of AI

AI is important because it:

  • Automates Repetitive Tasks → Saves time and reduces human error.

  • Enhances Decision-Making → Analyzes massive data faster than humans.

  • Improves Productivity → Helps industries like healthcare, finance, logistics.

  • Enables Innovation → New possibilities in personalized medicine, smart cities, etc.

  • Boosts Accessibility → AI-powered speech recognition, translation, and assistive tools.


3. Future Changes & Significance

AI is expected to transform society even more in the coming decades:

a) Economic Impact

  • Job Transformation: Some jobs will disappear (routine work), others will evolve (AI-assisted roles).

  • New Industries: AI-based services and products will become primary business drivers.

b) Technological Integration

  • AI will become embedded in every device — from homes to vehicles.

  • General AI (human-level intelligence) may emerge, enabling machines to adapt to any task.

c) Societal Effects

  • Better healthcare predictions, climate modeling, personalized education.

  • Ethical and legal challenges: privacy, bias, and accountability in AI decisions.

d) Long-Term Significance

  • AI will be as transformative as electricity or the internet — shaping how we work, live, and think.

  • Nations and companies that master AI will have significant global influence.


The future importance of AI in job industries will be massive, as it’s set to reshape what jobs exist, how they’re done, and the skills needed. Here’s a breakdown:




1. Automation of Routine Work

  • Impact: AI will take over repetitive, predictable tasks faster and with fewer errors.

  • Examples: Data entry, invoice processing, quality control, scheduling.

  • Result: Jobs heavy on manual repetition will decline, but humans will shift toward supervisory, creative, or analytical roles.


2. Creation of New Jobs

  • Impact: Just like the internet created jobs that didn’t exist before, AI will spawn new roles.

  • Examples:

    • AI model trainers & prompt engineers

    • Data annotators & AI ethics officers

    • AI maintenance and deployment specialists

  • Result: People who adapt to AI tools will be in high demand.


3. Decision Support & Augmentation

  • Impact: AI will help professionals make better, faster decisions by analyzing large datasets.

  • Examples:

    • Doctors using AI diagnostics

    • Lawyers using AI case research tools

    • Architects using AI-generated design concepts

  • Result: Higher productivity and accuracy in high-stakes fields.


4. Industry-by-Industry Transformation

  • Healthcare → Predictive diagnosis, robotic surgery assistance, personalized medicine.

  • Finance → Fraud detection, algorithmic trading, credit scoring.

  • Manufacturing → Predictive maintenance, AI-driven supply chains.

  • Retail & Marketing → Personalized recommendations, customer behavior prediction.

  • Education → AI tutors, adaptive learning platforms.


5. Skills Shift

  • From → Purely manual or repetitive technical skills.

  • To → AI management, creativity, problem-solving, emotional intelligence, and data literacy.


6. Long-Term Significance

  • AI will become as common in workplaces as email or the internet.

  • The human-AI collaboration model will be the norm: humans for creativity, ethics, empathy; AI for speed, scale, and data processing.

  • Countries & companies investing early in AI workforce training will dominate global competition.


i have created my own ai assistant using python 

code bellow:

Ibnsina AI — merged assistant with: - voice + GUI chat - search (DuckDuckGo + Google fallback) - top news (NewsAPI) - weather (OpenWeather) - open/close apps (dynamic + mapping) - WhatsApp/Telegram messaging (opens share links in browser) - YouTube search - uninstall (opens apps & features or tries WMIC) - shutdown/restart/sleep with confirmation - volume up/down (pycaw if available) - image generation stub (keeps your existing generate_image function) """ import string import psutil # pip install psutil # and your existing imports (tkinter, sr, pyttsx3, etc.) import os import sys import subprocess import time import datetime import webbrowser import json import requests import urllib.parse import re import tkinter as tk from tkinter import scrolledtext, messagebox import speech_recognition as sr import pyttsx3 import requests import json import os import subprocess import time import webbrowser import pyttsx3 import speech_recognition as sr # ... your other imports ... # 🔹 OpenRouter API settings API_KEY = "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" MODEL = "deepseek/deepseek-chat-v3-0324:free" API_URL = "https://openrouter.ai/api/v1/chat/completions" # --- Optional audio control (pycaw) --- try: from ctypes import cast, POINTER from comtypes import CLSCTX_ALL from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume PYA_AVAILABLE = True except Exception: PYA_AVAILABLE = False # --------- CONFIG: fill these ---------- NEWS_API_KEY = "03f08e6fbcbb45dcae183f59d0edb32a" # your NewsAPI key WEATHER_API_KEY = "ec3ff8ed818f521ac3ad33f2addf48ce" # your OpenWeather key GOOGLE_API_KEY = "AIzaSyB6vzz-SpCUVzB5nXdx9Mjag6Wg6cCH3Ok" # optional CSE key if you want programmatic Google search # -------------------------------------- # map common friendly names to executable paths (edit your paths here) APP_PATHS = { "whatsapp": r"C:\Users\ibnsi\AppData\Local\WhatsApp\WhatsApp.exe", "chrome": r"C:\Program Files\Google\Chrome\Application\chrome.exe", "vs code": r"C:\Users\ibnsi\AppData\Local\Programs\Microsoft VS Code\Code.exe", "vscode": r"C:\Users\ibnsi\AppData\Local\Programs\Microsoft VS Code\Code.exe", "notepad": r"notepad.exe", "calculator": r"calc.exe", "spotify": r"C:\Users\ibnsi\AppData\Roaming\Spotify\Spotify.exe", } # ------------- TTS -------------- engine = pyttsx3.init() engine.setProperty("rate", 170) def ask_openrouter(prompt): headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } data = { "model": MODEL, "messages": [{"role": "user", "content": prompt}] } try: response = requests.post(API_URL, headers=headers, json=data) response.raise_for_status() result = response.json() reply = result["choices"][0]["message"]["content"] return reply.strip() except Exception as e: return f"Error communicating with OpenRouter: {e}" import glob import os import subprocess import string def search_and_open_file(keyword): keyword = keyword.lower() drives = [] # Find drives on Windows (C:, D:, E: ...) for letter in string.ascii_uppercase: drive = f"{letter}:/" if os.path.exists(drive): drives.append(drive) for drive in drives: for root, dirs, files in os.walk(drive): for file in files: if keyword in file.lower(): file_path = os.path.join(root, file) try: # Use default app to open the file os.startfile(file_path) # Windows only return f"Opening file {file}" except Exception as e: return f"Failed to open file: {e}" return f"Couldn't find a file matching '{keyword}' on your drives." import os import subprocess import psutil # pip install psutil # ---------- OPEN FOLDER ---------- def open_folder(folder_path): if os.path.exists(folder_path): try: subprocess.Popen(f'explorer "{folder_path}"') return f"Opening folder: {folder_path}" except Exception as e: return f"Error opening folder: {e}" else: return f"Folder not found: {folder_path}" # ---------- CLOSE FOLDER ---------- def close_folder(folder_name): closed_any = False for proc in psutil.process_iter(['pid', 'name']): try: if proc.info['name'] and 'explorer.exe' in proc.info['name'].lower(): # On Windows, Explorer windows are all in one process proc.kill() closed_any = True break except (psutil.NoSuchProcess, psutil.AccessDenied): pass return "Closed all open folders." if closed_any else f"No folder window found for: {folder_name}" import os import subprocess import platform import os import subprocess import platform def open_file_or_app(file_path): try: if platform.system() == "Windows": os.startfile(file_path) elif platform.system() == "Darwin": subprocess.Popen(["open", file_path]) else: subprocess.Popen(["xdg-open", file_path]) return f"Opening {file_path}" except Exception as e: return f"Error opening file: {str(e)}" def search_and_open_file(file_name): drives = ["C:\\", "D:\\", "E:\\", "F:\\"] # You can add/remove drives for drive in drives: for root, dirs, files in os.walk(drive): if file_name.lower() in [f.lower() for f in files]: return open_file_or_app(os.path.join(root, file_name)) return f"Could not find {file_name}." def speak(text): """Speak and print to console (and GUI via reply()).""" try: engine.say(text) engine.runAndWait() except Exception: # TTS failures shouldn't stop the app print("TTS error.") print("Ibnsina:", text) # also insert into GUI if available via reply() # ------------- Utilities -------------- def reply(text): """Insert into GUI chat and speak (if GUI exists).""" print("Ibnsina:", text) try: # chat_area is created later; check existence if 'chat_area' in globals() and chat_area: chat_area.insert(tk.END, "Ibnsina: " + text + "\n") chat_area.see(tk.END) except Exception: pass # Speak after inserting to GUI speak(text) # ------------- Speech recognition ------------- def listen(timeout=None): r = sr.Recognizer() with sr.Microphone() as source: if timeout: audio = r.listen(source, timeout=timeout) else: audio = r.listen(source) try: text = r.recognize_google(audio) print("You (voice):", text) return text.lower() except sr.UnknownValueError: reply("Sorry, I didn't catch that.") return "" except sr.RequestError: reply("Speech recognition service failed.") return "" # ------------- Search & web helpers ------------- def duckduckgo_search(query): url = "https://api.duckduckgo.com/" params = {"q": query, "format": "json", "no_html": 1, "skip_disambig": 1} try: r = requests.get(url, params=params, timeout=8) if r.status_code == 200: data = r.json() if data.get("AbstractText"): return data["AbstractText"] if data.get("RelatedTopics"): first = data["RelatedTopics"][0] return first.get("Text", "No instant answer") return "I couldn't find an instant answer on DuckDuckGo." return f"DuckDuckGo error: {r.status_code}" except Exception as e: return f"DuckDuckGo error: {e}" def google_search_open(query): reply(f"Opening Google results for {query}") webbrowser.open(f"https://www.google.com/search?q={urllib.parse.quote_plus(query)}") def youtube_search_open(query): reply(f"Searching YouTube for {query}") webbrowser.open(f"https://www.youtube.com/results?search_query={urllib.parse.quote_plus(query)}") # ------------- News & Weather ------------- def get_top_news(): if not NEWS_API_KEY: reply("News API key not configured — opening news.google.com instead.") webbrowser.open("https://news.google.com") return url = "https://newsapi.org/v2/top-headlines" params = {"country": "us", "pageSize": 3, "apiKey": NEWS_API_KEY} try: r = requests.get(url, params=params, timeout=8) if r.status_code == 200: articles = r.json().get("articles", []) if not articles: reply("No top headlines found.") return reply("Here are the top headlines:") for a in articles: title = a.get("title", "No title") reply(title) else: reply(f"NewsAPI error {r.status_code}. Opening news site instead.") webbrowser.open("https://news.google.com") except Exception as e: reply(f"Failed to fetch news: {e}") def get_weather(lat=24.8, lon=88.9): if not WEATHER_API_KEY: reply("Weather API key not configured — I can't fetch weather.") return url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={WEATHER_API_KEY}&units=metric" try: r = requests.get(url, timeout=8) if r.status_code == 200: data = r.json() temp = data.get("main", {}).get("temp") descr = data.get("weather", [{}])[0].get("description", "") reply(f"Current temperature {temp}°C with {descr}.") else: reply("Weather API error.") except Exception as e: reply(f"Failed to fetch weather: {e}") # ---------- Volume control ---------- def set_volume(change): if not PYA_AVAILABLE: reply("pycaw not available — volume control requires pycaw module.") return try: devices = AudioUtilities.GetSpeakers() interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) current = volume.GetMasterVolumeLevelScalar() if change == "up": volume.SetMasterVolumeLevelScalar(min(1.0, current + 0.1), None) reply("Increased volume.") else: volume.SetMasterVolumeLevelScalar(max(0.0, current - 0.1), None) reply("Decreased volume.") except Exception as e: reply(f"Volume control failed: {e}") # ---------- Open / Close / Uninstall helpers ---------- def find_app_path(name): name_l = name.lower() # direct match first if name_l in APP_PATHS: return APP_PATHS[name_l] # partial match for k, v in APP_PATHS.items(): if k in name_l: return v return None def open_app(name): path = find_app_path(name) # special-case well-known web fallbacks if "whatsapp" in name.lower(): # try desktop exe first, then web fallback if path and os.path.exists(path): try: subprocess.Popen([path]) reply("Opening WhatsApp desktop.") return except Exception: pass # fallback to web webbrowser.open("https://web.whatsapp.com/") reply("Opened WhatsApp Web.") return if "telegram" in name.lower(): webbrowser.open("https://web.telegram.org/") reply("Opening Telegram Web.") return if "youtube" in name.lower(): webbrowser.open("https://www.youtube.com") reply("Opening YouTube.") return if path: if os.path.exists(path) or os.path.split(path)[-1].lower().endswith(".exe"): try: subprocess.Popen([path]) reply(f"Opening {name}.") except FileNotFoundError: reply(f"Path not found: {path}. Trying fallback by name.") try: os.startfile(path) reply(f"Opened {name}.") except Exception as e: reply(f"Failed to open {name}: {e}") else: # try startfile if it's in PATH (e.g., notepad.exe) try: os.startfile(path) reply(f"Opening {name}.") except Exception as e: reply(f"Failed to open {name}: {e}") else: # last resort: try to open by name (works for programs in PATH or registered apps) try: os.startfile(name) reply(f"Opening {name}.") except Exception: reply(f"Couldn't find an installed app for '{name}'. You can add its path to APP_PATHS in the script.") # as convenience, open Apps & features webbrowser.open("ms-settings:appsfeatures") def close_app(name): # attempt to choose reasonable exe name name_l = name.lower() exe = None # mapping common names if "chrome" in name_l: exe = "chrome.exe" elif "whatsapp" in name_l: exe = "WhatsApp.exe" elif "vs code" in name_l or "vscode" in name_l: exe = "Code.exe" elif "spotify" in name_l: exe = "Spotify.exe" else: # guess first token token = name_l.split()[0] exe = f"{token}.exe" try: os.system(f"taskkill /f /im {exe} >nul 2>&1") reply(f"Attempted to close {name} ({exe}).") except Exception as e: reply(f"Failed to close {name}: {e}") def uninstall_app(name): # confirmation if not confirm_action(f"Do you really want to uninstall '{name}'?"): reply("Uninstall cancelled.") return # try WMIC uninstall (may require admin and exact name) try: # use a LIKE query — not always reliable cmd = f'wmic product where "Name like \'%{name}%\'" call uninstall /nointeractive' p = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=60) out = p.stdout + p.stderr if "ReturnValue = 0" in out or p.returncode == 0: reply(f"Uninstall initiated for '{name}'. Follow any prompts.") return else: # fallback: open Apps & features reply("Could not uninstall automatically. Opening Apps & features; please uninstall manually.") webbrowser.open("ms-settings:appsfeatures") return except Exception as e: reply(f"Uninstall helper failed: {e}") webbrowser.open("ms-settings:appsfeatures") # ------------- Messaging helpers ------------- def send_whatsapp(phone_or_text, message=None): """ Usage: - If phone_or_text looks like a phone number (digits with optional +), open wa.me to that number with message. - Else open WhatsApp Web share with text. """ if re.fullmatch(r"[\+\d][\d]{6,15}", phone_or_text): phone = re.sub(r"[^\d+]", "", phone_or_text) if not message: message = "" url = f"https://wa.me/{phone}?text={urllib.parse.quote_plus(message)}" webbrowser.open(url) reply(f"Opening WhatsApp chat for {phone}. You may need to confirm/send in WhatsApp Web.") else: # treat phone_or_text as message text = phone_or_text if not message else message url = f"https://web.whatsapp.com/send?text={urllib.parse.quote_plus(text)}" webbrowser.open(url) reply("Opened WhatsApp Web share. Paste/select the contact and send manually.") def send_telegram(text, username=None): if username: # open chat for username (user may need to login to desktop app) url = f"https://t.me/{username}" webbrowser.open(url) reply(f"Opened Telegram chat with @{username}. You may need to paste the text manually.") else: url = f"https://t.me/share/url?url=&text={urllib.parse.quote_plus(text)}" webbrowser.open(url) reply("Opened Telegram share. Choose contact to send.") # ------------- Image generation stub (keep your existing implementation) ------------- def generate_image(prompt): # Keep your existing generation logic here or call your current function. # This is a placeholder. reply(f"Generating image for: {prompt} (stub).") # You can paste your generate_image implementation here. # ------------- Confirmation helper ------------- def confirm_action(prompt): """Return True if user confirms (GUI dialog -> yes), otherwise voice confirm.""" try: # if GUI exists, use messagebox if 'root' in globals() and root and root.winfo_exists(): return messagebox.askyesno("Confirm", prompt) except Exception: pass # voice mode fallback: ask and listen reply(prompt + " Say 'yes' to confirm.") ans = listen(timeout=5) return "yes" in ans.lower() # ------------- Main command dispatcher ------------- def _get_available_drives(): drives = [] for letter in string.ascii_uppercase: d = f"{letter}:\\" if os.path.exists(d): drives.append(d) return drives def search_and_open_file_by_keyword(keyword, max_results=10): """Search all available drives for files whose names contain `keyword` (case-insensitive). List up to max_results matches in chat and open the first match. Uses reply() and speak() to communicate with user. """ keyword = keyword.strip() if not keyword: reply("Please tell me which file to open.") return drives = _get_available_drives() matches = [] for drive in drives: for root, dirs, files in os.walk(drive): for f in files: if keyword.lower() in f.lower(): matches.append(os.path.join(root, f)) if len(matches) >= max_results: break if len(matches) >= max_results: break if len(matches) >= max_results: break if not matches: reply(f"Couldn't find any file containing '{keyword}' on your drives.") return # show found files (up to max_results) reply(f"Found {len(matches)} file(s) containing '{keyword}':") for i, p in enumerate(matches[:max_results], start=1): reply(f"{i}. {p}") # try to open first found file first = matches[0] try: os.startfile(first) reply(f"Opening: {first}") except Exception as e: reply(f"Failed to open {first}: {e}") def search_and_open_folder_by_keyword(keyword, max_results=10): """Search all available drives for folder names containing keyword (case-insensitive), list matches and open the first one.""" keyword = keyword.strip() if not keyword: reply("Please tell me which folder to open.") return drives = _get_available_drives() matches = [] for drive in drives: for root, dirs, files in os.walk(drive): for d in dirs: if keyword.lower() in d.lower(): matches.append(os.path.join(root, d)) if len(matches) >= max_results: break if len(matches) >= max_results: break if len(matches) >= max_results: break if not matches: reply(f"Couldn't find any folder containing '{keyword}' on your drives.") return reply(f"Found {len(matches)} folder(s) containing '{keyword}':") for i, p in enumerate(matches[:max_results], start=1): reply(f"{i}. {p}") first = matches[0] try: subprocess.Popen(['explorer', first]) reply(f"Opening folder: {first}") except Exception as e: reply(f"Failed to open folder {first}: {e}") def close_all_folders(): """Close all Explorer windows by terminating explorer.exe (Windows).""" closed_any = False for proc in psutil.process_iter(['pid', 'name']): try: if proc.info['name'] and 'explorer.exe' in proc.info['name'].lower(): proc.kill() closed_any = True except (psutil.NoSuchProcess, psutil.AccessDenied): pass reply("Closed all open folders." if closed_any else "No open folders found.") # --- The merged perform_task function --- def perform_task(command): if not command: return orig = command.strip() cmd = orig.lower() print("Performing:", cmd) # OPEN FILE (keyword search) if cmd.startswith("open file") or " open file " in cmd: # preserve original substring to keep paths as typed # e.g. "open file D:\Movies\clip.mp4" or "open file jum.mp4" # extract after the first occurrence of "open file" after = orig[cmd.find("open file") + len("open file"):].strip() # if user gave a path and it exists -> open directly if os.path.exists(after): try: os.startfile(after) reply(f"Opening file: {after}") except Exception as e: reply(f"Failed to open {after}: {e}") else: # search by keyword across drives search_and_open_file_by_keyword(after) return # OPEN FOLDER / DRIVE (accept full path or keyword) if cmd.startswith("open folder") or cmd.startswith("open drive"): after = orig[cmd.find("open folder") + len("open folder"):].strip() if "open folder" in cmd else orig[cmd.find("open drive") + len("open drive"):].strip() # if they provided a drive letter like "D" or "D:" or "D:\" if re.fullmatch(r"[A-Za-z]:\\?|[A-Za-z]$", after): # normalize to D:\ form drive = after[0].upper() + ":\\" if os.path.exists(drive): try: subprocess.Popen(['explorer', drive]) reply(f"Opening drive: {drive}") except Exception as e: reply(f"Failed to open drive {drive}: {e}") else: reply(f"Drive {drive} not found.") return # if exact path was provided and exists -> open it if os.path.exists(after): try: subprocess.Popen(['explorer', after]) reply(f"Opening folder: {after}") except Exception as e: reply(f"Error opening folder: {e}") return # otherwise treat the `after` as a folder-name keyword and search all drives search_and_open_folder_by_keyword(after) return # CLOSE FOLDER(S) if cmd.startswith("close all folders") or cmd == "close folders" or cmd == "close folder": close_all_folders() return # WEATHER if "weather" in cmd and "search" not in cmd: reply("Fetching weather...") get_weather() return # NEWS if "news" in cmd: get_top_news() return # SHUTDOWN / RESTART / SLEEP / LOCK if "shutdown" in cmd: if confirm_action("Are you sure you want to shut down the computer?"): reply("Shutting down now.") subprocess.call("shutdown /s /t 5", shell=True) else: reply("Shutdown cancelled.") return if "restart" in cmd: if confirm_action("Are you sure you want to restart the computer?"): reply("Restarting now.") subprocess.call("shutdown /r /t 5", shell=True) else: reply("Restart cancelled.") return if "sleep" in cmd or "suspend" in cmd: reply("Putting the computer to sleep.") subprocess.call("rundll32.exe powrprof.dll,SetSuspendState 0,1,0") return if "lock" in cmd: reply("Locking the computer.") subprocess.call("rundll32.exe user32.dll,LockWorkStation") return # VOLUME if "volume up" in cmd or "increase volume" in cmd: set_volume("up") return if "volume down" in cmd or "decrease volume" in cmd: set_volume("down") return # SEARCH FOR (DuckDuckGo w/ Google fallback) if "search for" in cmd: query = cmd.split("search for", 1)[-1].strip() if not query: reply("What would you like me to search for?") return reply(f"Searching DuckDuckGo for {query}...") res = duckduckgo_search(query) if isinstance(res, str) and ("couldn't find" in res.lower() or "error" in res.lower()): reply("Couldn't find instant answer — opening Google.") google_search_open(query) else: reply(res) return # YOUTUBE SEARCH if "search youtube for" in cmd or cmd.startswith("youtube search"): q = cmd.replace("search youtube for", "").replace("youtube search", "").strip() if q: youtube_search_open(q) else: reply("What do you want me to search on YouTube?") return # OPEN APP / WEBSITE (generic) if cmd.startswith("open "): target = orig[len("open "):].strip() # use original for path-like strings open_app(target) return # CLOSE APP if cmd.startswith("close "): target = orig[len("close "):].strip() close_app(target) return # UNINSTALL if cmd.startswith("uninstall ") or cmd.startswith("remove "): name = cmd.split(" ", 1)[1].strip() uninstall_app(name) return # SEND WHATSAPP if "send whatsapp" in cmd or "whatsapp message" in cmd: m = re.search(r"(?:send whatsapp(?: message)?(?: to)? )([\+\d\w@ ]+?)(?: (?:message|say) )(.+)", cmd) if m: to = m.group(1).strip() text = m.group(2).strip() if re.search(r"[\d\+]{7,}", to): send_whatsapp(to, text) else: send_whatsapp(text) else: reply("Please say: send whatsapp to <phone> <message> or send whatsapp <message>") return # SEND TELEGRAM if "send telegram" in cmd or "telegram message" in cmd: m = re.search(r"(?:send telegram(?: message)?(?: to)? )(@?\w+)?(?: )?(.*)", cmd) if m: username = m.group(1) text = m.group(2).strip() if username and text: send_telegram(text, username=username.lstrip("@")) elif text: send_telegram(text) else: reply("Please say: send telegram to <username> <message> or send telegram <message>") else: reply("Please provide recipient and message.") return # GENERATE / DRAW IMAGE if "generate image" in cmd or cmd.startswith("draw "): prompt = orig.replace("generate image", "").replace("draw", "").strip() if prompt: generate_image(prompt) else: reply("Please tell me what to draw.") return # PERSONAL INFO / SMALL TALK if "your name" in cmd: reply("I am Ibnsina, your assistant.") return if "time" in cmd: now = datetime.datetime.now().strftime("%I:%M %p") reply(f"The time is {now}.") return if "birth date" in cmd or "birthday" in cmd: speak("I was born on 31st December 2000.") return if "where" in cmd and "live" in cmd: speak("I live in Naogaon, Bangladesh.") return if "father" in cmd and "name" in cmd: speak("My father's name is Shariful Islam Hera.") return if "mother" in cmd and "name" in cmd: speak("My mother's name is Wahida Akter Smrity.") return if "religion" in cmd: speak("I trust in Islam.") return if "tell me a joke" in cmd: speak("Why did the computer go to therapy? It had too many bytes from its past.") return # FALLBACK: AI REPLY (OpenRouter) or Google search ai_reply = ask_openrouter(orig) if ai_reply and not ai_reply.lower().startswith("error"): speak(ai_reply) else: reply("I couldn't match a specific command. I'll search the web for that.") google_search_open(cmd) # -------------- GUI & main loop --------------- def send_message(): user_input = entry.get() if not user_input.strip(): return chat_area.insert(tk.END, "You: " + user_input + "\n") chat_area.see(tk.END) entry.delete(0, tk.END) perform_task(user_input) def listen_command(): chat_area.insert(tk.END, "You (voice): ...\n") chat_area.see(tk.END) cmd = listen() if cmd: chat_area.insert(tk.END, "You (voice): " + cmd + "\n") chat_area.see(tk.END) perform_task(cmd) # Build GUI root = tk.Tk() root.title("Ibnsina AI Assistant") root.geometry("760x520") chat_area = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=90, height=24, font=("Arial", 11)) chat_area.pack(padx=8, pady=8) bottom_frame = tk.Frame(root) bottom_frame.pack(fill=tk.X, padx=8, pady=(0,8)) entry = tk.Entry(bottom_frame, width=60, font=("Arial", 12)) entry.pack(side=tk.LEFT, padx=(0,8)) entry.bind("<Return>", lambda e: send_message()) send_btn = tk.Button(bottom_frame, text="Send", width=10, command=send_message) send_btn.pack(side=tk.LEFT, padx=(0,8)) voice_btn = tk.Button(bottom_frame, text="🎤 Voice", width=10, command=listen_command) voice_btn.pack(side=tk.LEFT) # optionally add quick action buttons tk.Button(bottom_frame, text="News", command=lambda: perform_task("news")).pack(side=tk.LEFT, padx=4) tk.Button(bottom_frame, text="Weather", command=lambda: perform_task("weather")).pack(side=tk.LEFT, padx=4) # Start reply("Ibnsina is ready. Type or press Voice to speak.") root.mainloop()




Functionalities of My AI

1. Speech & Text Interaction

  • Voice Recognition → Listens to the user via microphone using speech_recognition.

  • Text-to-Speech (TTS) → Talks back using pyttsx3 with adjustable voice and rate.

  • GUI Chatbox → Tkinter-based interface for typing and reading AI responses.


2. Information Retrieval

  • News Updates → Fetches top headlines from NewsAPI.

  • Weather Reports → Retrieves real-time weather from OpenWeather API.

  • Web Search → Searches using DuckDuckGo, with Google as fallback.

  • YouTube Search → Opens YouTube search results in browser.


3. AI-Powered Responses

  • OpenAI Chat → Answers general questions, explains concepts, or generates text.

  • Google Gemini API → Can generate text or images based on prompts.

  • HuggingFace & DALL·E → Supports AI image generation.


4. Computer Control & App Management

  • Open Applications → Launches installed programs dynamically.

  • Close Applications → Kills running processes.

  • Uninstall Apps → Opens Windows uninstall interface or uses WMIC.

  • Volume Control → Adjusts system sound using Pycaw.

  • Open Websites → Directly navigates to requested sites.


5. Image Generation

  • Generates images from text prompts using Gemini, DALL·E, or HuggingFace models.


6. Additional Features

  • Clipboard & File Handling → Basic text output and saved files (images, etc.).

  • Error Handling → Checks for missing API responses, invalid inputs, or failed requests.

  • Interactive GUI → Chat history display, scrollable interface, and input field.

few output images:







If you want to have ai with key word to operate then use this bellow code. in this code it will ask you to chat or talk. to chat type chat. to talk tap on enter:
import requests import json import speech_recognition as sr import pyttsx3 import subprocess import time import webbrowser import os from ctypes import cast, POINTER from comtypes import CLSCTX_ALL from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume import tkinter as tk from tkinter import scrolledtext import base64 import google.generativeai as genai from dotenv import load_dotenv import os load_dotenv() api_key = os.getenv("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") import openai openai.api_key = api_key import openai openai.api_key = "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" import requests from PIL import Image from io import BytesIO import google.generativeai as genai from PIL import Image import io # Configure Gemini genai.configure(api_key="AIzaSyCL5PuHcwaSsWCPJxtwNmxGHEcFxfei9QQ") # Replace with your real key # Text-to-Image generation from PIL import Image from io import BytesIO import PIL.Image def generate_image(prompt): import requests from PIL import Image from io import BytesIO import time url = "https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5" headers = {"Accept": "application/json"} data = {"inputs": prompt} try: response = requests.post(url, headers=headers, json=data) if response.status_code == 200: image = Image.open(BytesIO(response.content)) filename = f"generated_{int(time.time())}.png" image.save(filename) image.show() else: print("Ibnsina: Failed to generate image.") print("Response:", response.text) except Exception as e: print("Ibnsina: Error occurred while generating image:", e) # ====== Configuration ====== API_KEY = "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" MODEL = "deepseek/deepseek-chat-v3-0324:free" API_URL = "https://openrouter.ai/api/v1/chat/completions" NEWS_API_KEY = "03f08e6fbcbb45dcae183f59d0edb32a" WEATHER_API_KEY = "ec3ff8ed818f521ac3ad33f2addf48ce" HEADERS = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json", "HTTP-Referer": "https://ibnsina.local", "X-Title": "Ibnsina AI Assistant" } GOOGLE_API_KEY = "AIzaSyB6vzz-SpCUVzB5nXdx9Mjag6Wg6cCH3Ok" PRIMARY_CX = "57a746b5f10134e3c" FALLBACK_CX = "017576662512468239146:omuauf_lfve" engine = pyttsx3.init() engine.setProperty("rate", 180) def speak(text): print("Ibnsina:", text) engine.say(text) engine.runAndWait() def listen(): recognizer = sr.Recognizer() with sr.Microphone() as source: print("Listening for command...") audio = recognizer.listen(source) try: command = recognizer.recognize_google(audio) print("You:", command) return command.lower() except sr.UnknownValueError: speak("Sorry, I didn't catch that.") return "" except sr.RequestError: speak("Error with internet connection.") return "" def passive_listen(): recognizer = sr.Recognizer() with sr.Microphone() as source: print("Waiting for hotword: 'hello'...") try: audio = recognizer.listen(source, timeout=5) trigger = recognizer.recognize_google(audio).lower() print("Heard:", trigger) return "hello" in trigger except sr.WaitTimeoutError: print("No speech detected (timeout).") return False except sr.UnknownValueError: print("Could not understand audio.") return False except sr.RequestError as e: print(f"Google Speech Recognition error: {e}") speak("Speech recognition failed due to a network issue.") return False def duckduckgo_search(query): url = "https://api.duckduckgo.com/" params = { "q": query, "format": "json", "no_html": 1, "skip_disambig": 1 } try: response = requests.get(url, params=params) if response.status_code == 200: data = response.json() # Prefer Abstract if available if data.get("AbstractText"): result = data["AbstractText"] speak(result) print("🔎 DuckDuckGo:", result) return result # If no abstract, check related topics elif data.get("RelatedTopics"): first_topic = data["RelatedTopics"][0] if "Text" in first_topic: result = first_topic["Text"] speak(result) print("🔎 DuckDuckGo:", result) return result return "I couldn't find an instant answer on DuckDuckGo." else: return f"Error {response.status_code} from DuckDuckGo API." except Exception as e: return f"Error fetching DuckDuckGo results: {e}" def google_search(query): def try_search(cse_id): url = "https://www.googleapis.com/customsearch/v1" params = { "key": GOOGLE_API_KEY, "cx": cse_id, "q": query } response = requests.get(url, params=params) if response.status_code == 200: items = response.json().get("items", []) if items: result = items[0] speak(f"Top result: {result['title']}") speak(f"You can visit: {result['link']}") print(f"🔗 {result['title']} → {result['link']}") return True return False if not try_search(PRIMARY_CX): speak("Trying fallback search engine...") if not try_search(FALLBACK_CX): speak("Sorry, I couldn't find anything.") def insert_formatted_response(text): """Formats and inserts AI responses into the chat area, preserving code blocks.""" if "```" in text: parts = text.split("```") for i, part in enumerate(parts): if i % 2 == 1: # Code block chat_area.insert(tk.END, "\n[Code Block]\n" + part.strip() + "\n\n") else: chat_area.insert(tk.END, "Ibnsina: " + part.strip() + "\n") else: chat_area.insert(tk.END, "Ibnsina: " + text.strip() + "\n") def get_top_news(): url = "https://newsapi.org/v2/top-headlines" params = { "country": "us", "pageSize": 3, "apiKey": NEWS_API_KEY } response = requests.get(url, params=params) if response.status_code == 200: articles = response.json().get("articles", []) if not articles: speak("No news found.") return speak("Here are the top headlines:") for article in articles: title = article.get("title", "No title") print("📰", title) speak(title) else: speak("Failed to fetch news.") print("NewsAPI error:", response.status_code, response.text) def get_weather(lat=24.8, lon=88.9): # Default coordinates for Naogaon url = f"https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&exclude=minutely,hourly,daily,alerts&appid={WEATHER_API_KEY}&units=metric" response = requests.get(url) if response.status_code == 200: data = response.json() current = data.get("current", {}) temp = current.get("temp") weather = current.get("weather", [{}])[0].get("description", "No description") speak(f"The current temperature is {temp} degrees Celsius with {weather}.") else: speak("Failed to retrieve weather information.") print("WeatherAPI error:", response.status_code, response.text) import re def ask_ibnsina(prompt): payload = { "model": MODEL, "messages": [ {"role": "system", "content": "You are Ibnsina, a helpful AI assistant. Answer clearly and naturally. Format code using triple backticks (` ``` `)."}, {"role": "user", "content": prompt} ] } response = requests.post(API_URL, headers=HEADERS, data=json.dumps(payload)) if response.status_code == 200: raw_text = response.json()['choices'][0]['message']['content'] return clean_response(raw_text) else: return f"API Error: {response.status_code}" import re def clean_response(text): # Preserve code formatting by handling triple backticks text = re.sub(r'```(?:\w+)?', '```', text) # Normalize ```language to ``` text = re.sub(r'[^\x00-\x7F]+', '', text) # Remove non-ASCII chars (e.g., emojis) return text.strip() def set_volume(change): devices = AudioUtilities.GetSpeakers() interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) current = volume.GetMasterVolumeLevelScalar() if change == "up": volume.SetMasterVolumeLevelScalar(min(1.0, current + 0.1), None) elif change == "down": volume.SetMasterVolumeLevelScalar(max(0.0, current - 0.1), None) def perform_task(command): if "weather" in command: get_weather() elif "open whatsapp" in command: subprocess.Popen(["C:\\Users\\ibnsi\\AppData\\Local\\WhatsApp\\WhatsApp.exe"]) speak("Opening WhatsApp.") elif "open youtube" in command: webbrowser.open("https://www.youtube.com") speak("Opening YouTube.") elif "open chrome" in command: subprocess.Popen(["C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"]) speak("Opening Chrome.") elif "open vs code" in command: subprocess.Popen(["C:\\Users\\ibnsi\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"]) speak("Opening Visual Studio Code.") elif "shutdown" in command: speak("Shutting down the computer.") subprocess.call("shutdown /s /t 1", shell=True) elif "restart" in command: speak("Restarting the computer.") subprocess.call("shutdown /r /t 1", shell=True) elif "sleep" in command: speak("Putting the computer to sleep.") subprocess.call("rundll32.exe powrprof.dll,SetSuspendState 0,1,0") elif "lock" in command: speak("Locking the computer.") subprocess.call("rundll32.exe user32.dll,LockWorkStation") elif "volume up" in command: set_volume("up") speak("Increasing volume.") elif "volume down" in command: set_volume("down") speak("Decreasing volume.") elif command.startswith("open "): app_name = command.replace("open ", "").strip().lower() speak(f"Opening {app_name}...") try: os.startfile(app_name) # works for apps in PATH or .lnk shortcuts except FileNotFoundError: speak(f"Sorry, I couldn't find {app_name}.") elif command.startswith("close "): app_name = command.replace("close ", "").strip().lower() speak(f"Closing {app_name}...") os.system(f"taskkill /f /im {app_name}.exe") elif "search for" in command: query = command.split("search for")[-1].strip() speak(f"Searching DuckDuckGo for {query}...") result = duckduckgo_search(query) # If DuckDuckGo fails, use Google search if "couldn't find" in result.lower() or "error" in result.lower(): speak("Switching to Google search...") google_search(query) elif "news" in command: get_top_news() elif "your name" in command: speak("I am Ibnsina, your assistant.") elif "birth date" in command or "birthday" in command: speak("I was born on 31st December 2000.") elif "where" in command and "live" in command: speak("I live in Naogaon, Bangladesh.") elif "father" in command and "name" in command: speak("My father's name is Shariful Islam Hera.") elif "mother" in command and "name" in command: speak("My mother's name is Wahida Akter Smrity.") elif "religion" in command: speak("I trust in Islam.") elif "tell me a joke" in command: speak("Why did the computer go to therapy? It had too many bytes from its past.") elif "draw" in command or "generate image" in command: prompt = command.replace("draw", "").replace("generate image", "").strip() speak("Generating an image. Please wait...") generate_image(prompt) else: response = ask_ibnsina(command) speak(response) # ====== GUI Chatbox ====== def send_message(): user_input = entry.get() if not user_input.strip(): return chat_area.insert(tk.END, "You: " + user_input + "\n") entry.delete(0, tk.END) user_input_lower = user_input.lower() if "news" in user_input_lower: chat_area.insert(tk.END, "Ibnsina: Fetching the latest news...\n") get_top_news() elif "weather" in user_input_lower: chat_area.insert(tk.END, "Ibnsina: Checking the weather...\n") get_weather() elif "search for" in user_input_lower: query = user_input_lower.split("search for")[-1].strip() if query: chat_area.insert(tk.END, f"Ibnsina: Searching DuckDuckGo for {query}...\n") result = duckduckgo_search(query) if "couldn't find" in result.lower() or "error" in result.lower(): chat_area.insert(tk.END, "Ibnsina: Switching to Google search...\n") google_search(query) else: chat_area.insert(tk.END, "Ibnsina: Please specify a search query.\n") elif "generate image" in user_input_lower or "draw" in user_input_lower: prompt = user_input_lower.replace("generate image", "").replace("draw", "").strip() if prompt: chat_area.insert(tk.END, f"Ibnsina: Generating image of '{prompt}'...\n") generate_image(prompt) else: chat_area.insert(tk.END, "Ibnsina: Please describe what you want to draw.\n") else: response = ask_ibnsina(user_input) insert_formatted_response(response) # Now properly defined speak(response) # Optional: Voice response def launch_chat_gui(): global entry, chat_area window = tk.Tk() window.title("Ibnsina AI Assistant") chat_area = scrolledtext.ScrolledText(window, wrap=tk.WORD, width=60, height=20, font=("Arial", 12)) chat_area.pack(padx=10, pady=10) entry_frame = tk.Frame(window) entry_frame.pack(padx=10, pady=(0, 10)) entry = tk.Entry(entry_frame, width=45, font=("Arial", 12)) entry.pack(side=tk.LEFT, padx=(0, 10)) entry.bind("<Return>", lambda event: send_message()) send_button = tk.Button(entry_frame, text="Send", command=send_message, font=("Arial", 12)) send_button.pack(side=tk.RIGHT) window.mainloop() # ====== Main ====== if __name__ == "__main__": mode = input("Type 'chat' for chatbox mode or press Enter for voice mode: ").strip().lower() if mode == "chat": launch_chat_gui() else: speak("Ibnsina is ready. Say 'Hello' to activate me.") while True: if passive_listen(): speak("Yes, how can I help you?") command = listen() if command in ["exit", "quit", "stop"]: speak("Goodbye.") break perform_task(command) time.sleep(1)





✅ In short, this AI acts as a voice + text assistant with internet search, news, weather, app control, and AI-generated text & images, all inside a GUI.





Post a Comment

0 Comments