diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,39 +1,54 @@ -from encodings import utf_8 import os -from pickle import POP import gradio as gr import openai +#from numpy._core.defchararray import endswith, isdecimal, startswith from openai import OpenAI from dotenv import load_dotenv from pathlib import Path from time import sleep -# import audioread -# import queue -# import threading +import audioread +import queue +import threading from glob import glob +import copy +import base64 import json +from PIL import Image +from io import BytesIO +from pydantic import BaseModel +import pprint +import pandas as pd +import yfinance as yf from datetime import datetime, timedelta -import sqlite3 -import struct -import re -from dateutil.parser import * -from openai.lib import azure -from pydantic.type_adapter import R import pytz +import math +import numpy as np +from pylatexenc.latex2text import LatexNodes2Text import requests -import boto3 +from urllib.parse import quote +import geo_distance +import geo_locate +import time + +TOP_MODEL = "gpt-6-astra" +MIDDLE_MODEL = "gpt-6.1-sol" +LOW_MODEL = "gpt-6-luna" +MATH_MODEL = TOP_MODEL +DEFAULT_MODEL = MIDDLE_MODEL +IMAGE_MODEL = "gpt-image-2.5-flare" +IMAGE_MODEL_BEST = "gpt-image-2.5-sunburst" load_dotenv(override=True) key = os.getenv('OPENAI_API_KEY') -# keyb = os.getenv('OPENAI_API_KEYB') users = os.getenv('LOGNAME') unames = users.split(',') pwds = os.getenv('PASSWORD') pwdList = pwds.split(',') -google_translate_key = os.getenv('GOOGLE_KEY') -amazon_access_id = os.getenv('AMAZON_ACCESS_ID') -amazon_access_secret = os.getenv('AMAZON_ACCESS_SECRET') -azure_key = os.getenv('AZURE_KEY') +DEEPSEEK_KEY=os.getenv('DEEPSEEK_KEY') +GROQ_KEY=os.getenv('GROQ_KEY') +BRAVE_KEY=os.getenv('BRAVE_KEY') +BRAVE_SEARCH_KEY=os.getenv('BRAVE_SEARCH_KEY') +LOCATIONID_KEY=os.getenv('LOCATIONID_KEY') site = os.getenv('SITE') if site == 'local': @@ -44,26 +59,13 @@ else: dp = Path('/data') dp.mkdir(exist_ok=True) dataDir = '/data/' +stock_data_path = dataDir + 'Stocks.txt' -def make_db_array(): - db_paths = glob(dataDir + '*.db') - db_list = [] - # db_list.append('All Teaching Topics') - for path in db_paths: - db_name = os.path.basename(path)[:-3] - if 'isr' in db_name.lower() and 'bible' in db_name.lower(): - continue - db_list.append(db_name) - db_list_clean = db_list.copy() - while len(db_list)%3: - db_list.append("") - rows, cols = int(len(db_list)/3), 3 - arr = [[db_list[r*3 + c] for c in range(cols)] for r in range(rows)] - return (arr, db_list_clean) - -db_array, db_list = make_db_array() +braveNewsEndpoint = "https://api.search.brave.com/res/v1/news/search" +braveSearchEndpoint = "https://api.search.brave.com/res/v1/web/search" speak_file = dataDir + "speek.wav" +email_file = dataDir + "email.txt" # client = OpenAI(api_key = key) @@ -71,507 +73,642 @@ speak_file = dataDir + "speek.wav" abbrevs = {'St. ' : 'Saint ', 'Mr. ': 'mister ', 'Mrs. ':'mussus ', 'Mr. ':'mister ', 'Ms. ':'mizz '} -languages ={'en':'English', 'es':'Spanish', 'de':'German', 'fr':'French', 'zh':'Chinese', 'ro':'Romanian', - 'ja':'Japanese', 'he':'Hebrew', 'af':'Afrikaans'} +special_chat_types = ['math', 'logic'] -button_names = {"Marriage and Divorce": "Divorce, Remarriage & Putting Away", - "Are U Covenanted": "Are You Covenanted?", - "False Prophets": "Beware False Prophets (Identifying the Anti-Messiah)", - "Father and Son": "Do You Know the Father and the Son?", - "Good News": "What is the Good News?", - "HaSatan": "HaSatan (Did the Devil Make You Do It?)", - "The Heart": "The Heart of the Matter" - } +news_interval_choices = [("Day", "pd"), ("Week", "pw"), ("Month", "pm"), ("Year", "py")] -relevance_terms = [ - 'Probably little connection', - 'Questionable relevance', - 'May be relevant', - 'Probably relevant', - 'Likely highly relevant' -] - -def populate_book_chooser(checked: bool, bible_books: {}): - books = [] - for book in bible_books.keys(): - books.append(book) - return [gr.Dropdown(visible=checked, choices=books, interactive=checked, value=None), checked] - -def get_bible_verse(book: str, chapter: str, verse_num: str)->str: - verse_num = int(verse_num) - rv = '' - conn = sqlite3.connect(dataDir + 'ISR_bible.db') - cur = conn.cursor() - query = f'SELECT * from embeds where book = ? and chapter = ?' - result = cur.execute(query, (book, chapter) ) - for row in result.fetchall(): - verse_range = row[2] - (n1, n2) = verse_range.split('-') - if verse_num >= int(n1) and verse_num <= int(n2): - verse_text = row[3] - rv = verse_text - break; - conn.close() - return rv +def store_email(etext: str) -> str: + count = '' + try: + with open(email_file, 'wb') as efile: + count = str(efile.write(etext.encode('utf-8') ) ) + except: + count = 'Error storing edata' + return count + +def create_file(file_path): + with open(file_path, "rb") as file_content: + result = Client().files.create( + file=file_content, + purpose="vision", + ) + return result.id -def parse_verse_refs(txt: str, reverse_bible_books)->[]: - subs = {'1 ':'First ', '2 ':'Second ', '3 ':' Third'} - rv = [] - pattern = r'\{(.+),(.+),(.+),(.+)\}' - ml = re.findall(pattern, txt) - for (n, bk, ch, vs) in ml: +def read_email()->str: + etext = '' + try: + with open(email_file, 'rb') as efile: + etext_b = efile.read() + etext = etext_b.decode('utf-8') + except Exception as e: + etext = f'Error getting etext: {e}' + if etext.strip() == 'email_data': + etext = 'Error: no email available' + return etext + +def parse_email_meta(edata: str)->str: + meta_list = '' + mails = edata.split('===========') + for mail in mails: + loc1 = mail.find('From: ') + # loc1 = mail.find('Subject: ') + if loc1> -1: + loc2 = mail.find('Body:') + if loc2 > loc1: + meta_list += (mail[loc1:loc2].replace('From:','**From:** ').replace('Subject:','**Subject:** ').replace('Received:','**Received:** ') + '\n') + return meta_list + +def truncate_email(edata: str)->(str, str): + t_size = 0 + t_max = 250000 + status = 'ok' + last_date = '' + mails = edata.split('===========') + out_list = [] + for mail in mails: + if t_size > t_max: + break + t_size += len(mail) + 11 + loc = mail.find('Received: ') + if loc > 0: + loc2 = mail.find('Body:') + if loc2 > loc + 9: + last_date = mail[loc+10:loc2][:19] + out_list.append(mail) + t_mail = '==========='.join(out_list) + return (t_mail, last_date) + +def get_distance(addr1, addr2): + (lat1, lon1) = geo_locate.get_geo_coords(addr1, LOCATIONID_KEY) + (lat2, lon2) = geo_locate.get_geo_coords(addr2, LOCATIONID_KEY) + distance = geo_distance.great_circle_distance_miles(lat1, lon1, lat2, lon2) + return distance + +def get_openai_file(file_id, container_id): + url = f'https://api.openai.com/v1/containers/{container_id}/files/{file_id}/content' + headers= {"Authorization": "Bearer " + key} + + response = requests.get( + url, + headers=headers + ) + return response + +def list_openai_container_files(container_id): + url = f'https://api.openai.com/v1/containers/{container_id}/files' + headers= {"Authorization": "Bearer " + key} + + response = requests.get( + url, + headers=headers + ) + return response + +def create_openai_container(name): + url = 'https://api.openai.com/v1/containers' + headers= {"Authorization": "Bearer " + key, "Content-Type": "application/json",} + json_data = {"name": name} + + response = requests.post( + url, + headers=headers, + json=json_data + ) + + return json.loads(response.content)["id"] + + +class Step(BaseModel): + explanation: str + output: str + +class MathReasoning(BaseModel): + steps: list[Step] + final_answer: str + +def get_brave_search_results(query: str): + rv = '' + url = f'{braveSearchEndpoint}?q={quote(query)}&count=20' + response = requests.get( + url, + headers= {"Accept": "application/json", + "X-Subscription-Token": BRAVE_KEY + }, + ) + rv ='''Following are list items delineated by *item separator* +At the end of each item is (item source, item age) +*item separator* ''' + jdata = response.json() + web_results = jdata['web']['results'] + for item in web_results: + title = item['title'] + description = item['description'] + rv += f'{title}: {description} --' + try: # extra_snippets can be missing + for snip in item['extra_snippets']: + rv += (snip + ' ') + except: + pass try: - if '#' in n: - continue - if 'chunk' in n.casefold(): - chunk_num = int(n.strip().split()[1]) - else: - chunk_num = int(n.strip()) - book = bk.strip() - for c in ['1 ','2 ','3 ']: - if book.startswith(c): - book = book.replace(c, subs[c]) - short_book = reverse_bible_books.get(book.casefold(), None) - chapter = int(ch.strip()) - verse = int(vs.strip()) - if short_book: - rv.append( (chunk_num, short_book, chapter, verse) ) + host = item['meta_url']['hostname'] except: - continue - return rv + host = 'unknown' + try: + age = item['age'] + except: + age = 'unknown' + rv += f' (Item source: {host}, Item age: {age})' + rv += ' *item separator* ' -def check_books(filter: bool, books: []): - if books == None and filter: - return md('
Warning: You enabled bible book filter but have no books selected in filter
\n') - else: - return 'ok' - -def on_db_change(db_name: str, bible_books: {}, book_filter_active: bool): - date_vis = True - bible_vis = False - books = [] - show_accordian = (db_name == 'Selected Teachings') - for key in bible_books.keys(): - books.append(key) - if 'ISR' in db_name: - date_vis = False - bible_vis = True - else: - book_filter_active = False; - return [gr.Markdown(visible=date_vis), gr.Textbox(visible=date_vis), - gr.Textbox(visible=date_vis), - gr.Dropdown(visible=bible_vis and book_filter_active, choices=books, interactive=True), - gr.Checkbox(visible=bible_vis, value=book_filter_active), - gr.Checkbox(visible=date_vis, value=False), - book_filter_active, - gr.Group(visible=show_accordian)] - -def make_sorted_passages(passages, bible_books): - numbered_passages = [] - for passage in passages: - (book, chapter, verse_range, verse, dp) = passage - (book_num, book) = bible_books.get(book, (0, 'Unknown') ) - book_num *= 100000 - chap_num = int(chapter) * 1000 - verses = verse_range.split('-') - verse_num = int(verses[0].strip()) - sort_num = book_num + chap_num + verse_num - relevance = get_relevance_number(dp) - numbered_passages.append( (sort_num, book, chapter, verse_range, verse, relevance) ) - sorted_passages = sorted(numbered_passages) - return sorted_passages - -def get_relevance_number(dp: float)->int: - rv = 0 - if dp > 0.6: - rv = 4 - elif dp > 0.5: - rv = 3 - elif dp > 0.4: - rv = 2 - elif dp > 0.3: - rv = 1 return rv -def make_hebrew(prompt: str, en_hebrew: {})->str: - prompt = prompt.casefold() - for (key, val) in en_hebrew.items(): - key = key.casefold() - if key in prompt: - prompt = prompt.replace(key, val) - return prompt - -def update_translation_count(count, language): - if language != 'en': - return count - else: - return 0 - - -def azure_translate_text(text, target_language, source_language = 'en'): - if target_language == source_language: - return text - path = '/translate' - endpoint = 'https://api.cognitive.microsofttranslator.com' - constructed_url = endpoint + path - - headers = { - 'Ocp-Apim-Subscription-Key': azure_key, - 'Ocp-Apim-Subscription-Region': 'eastus', #'East US' - 'Content-Type': 'application/json', - } - - body = [{ - 'text': text - }] - - params = { - 'api-version': '3.0', - 'to': target_language - } - - response = requests.post(constructed_url, headers=headers, params=params, json=body) - response.raise_for_status() - return response.json()[0]['translations'][0]['text'] - -def translate_text(text_list, target_lang): # Amazon translate - client = boto3.client( - 'translate', - aws_access_key_id=amazon_access_id, - aws_secret_access_key=amazon_access_secret, - region_name='us-east-1' - ) - - rv = '' - for text in text_list: - result = client.translate_text( - Text=text, - SourceLanguageCode='en', - TargetLanguageCode=target_lang + +def get_brave_news(query: str, interval: str = 'pd'): + url = f'{braveNewsEndpoint}?q={quote(query)}&count=20&extra_snippets=true&freshness={interval}' + response = requests.get( + url, + headers= {"Accept": "application/json", + "X-Subscription-Token": BRAVE_KEY + }, ) - temp = result['TranslatedText'] - rv += temp + rv ='''Following are list items delineated by *item separator* +At the end of each item is (item source, item age) +*item separator* ''' + jdata = response.json() + for item in jdata['results']: + title = item['title'] + description = item['description'] + rv += f'{title}: {description} --' + try: # extra_snippets can be missing + for snip in item['extra_snippets']: + rv += (snip + ' ') + except: + pass + try: + host = item['meta_url']['hostname'] + except: + host = 'unknown' + try: + age = item['age'] + except: + age = 'unknown' + rv += f' (Item source: {host}, Item age: {age})' + rv += ' *item separator* ' return rv +def Client(): + return OpenAI(api_key = key) -def get_translation(text: str, language: str): # Google translate - params = { - 'q': text, - 'source': 'en', - 'target': language, - 'format': 'text', - 'key': google_translate_key +def test_plot_df(): + data = { + "month": ['2024-01','2024-02','2024-03'], + "value": [22.4, 30.1, 25.6] } + return pd.DataFrame(data) - response = requests.post( - 'https://translation.googleapis.com/language/translate/v2', - data=params - ) - if response.status_code == 200: - translation = response.json()['data']['translations'][0]['translatedText'] - return translation - else: - return 'translation failed' +def md(txt): + # if 'DOCTYPE' in txt: + # return str(txt.replace('GPT','
GPT')) + # else: + return str(txt).replace('```', ' ').replace(' ', '  ').replace(' ', '  ').replace(' ', '  ').replace('\n','
').replace('~~','~') + # return txt def etz_now(): eastern = pytz.timezone('US/Eastern') ltime = datetime.now(eastern) - return ltime.strftime('%Y-%m-%d') + return ltime -def populate_bible_books(bible_books, reverse_bible_books): - rv = True - if len(bible_books) == 66: - return (rv, bible_books, reverse_bible_books) - try: - bible_books = {} - reverse_bible_books = {} - path = Path(dataDir + 'BibleBooks.txt') - if path.is_file(): - with open(path, 'rt', encoding='utf-8') as fp: - lines = fp.readlines() - book_num = 0 - for line in lines: - if line.startswith('#'): - continue - book_num += 1 - items = line.split(',') - short_name = items[0].strip() - long_name = items[1].strip() - bible_books[short_name] = (book_num, long_name) - reverse_bible_books[long_name.casefold()] = short_name +def date_from_utime(utime): + ts = int(utime) + dt = datetime.utcfromtimestamp(ts) + eastern = pytz.timezone('US/Eastern') + return dt.astimezone(eastern).strftime('%Y-%m-%d') + +def convert_latex_math(text): + lines = text.split('\n') + start_line = False + out_txt = '' + for line in lines: + if len(line) == 0: + out_txt += '\n' + continue else: - bible_books = {} - reverse_bible_books = {} - rv = False + if line == r'\]': + continue + if line == r'\[': + start_line = True + continue + if start_line: + line = '\n' + LatexNodes2Text().latex_to_text(line.strip()) + start_line = False + if line.startswith(r'\['): + loc = line.find(r'\]') + if loc > 0: + latex_code = line[2:loc] + line = '\n' + LatexNodes2Text().latex_to_text(latex_code) + out_txt += (line + '\n') + return out_txt + +def stock_list(): + rv = '' + with open(stock_data_path, 'rt') as fp: + lines = fp.readlines() + for line in lines: + (name, symbol, shares) = line.rstrip().split(',') + name = name.strip() + symbol = symbol.strip() + rv += f'{symbol} {name}\n' + return rv + +def get_stock_list(): + stock_list = {} + with open(stock_data_path, 'rt') as fp: + lines = fp.readlines() + for line in lines: + (name, symbol, shares) = line.rstrip().split(',') + stock_list[symbol.strip()] = (name.strip(),shares.strip()) + return stock_list + +def get_stock_news(search_symbol): + fuzzy = True + have_symbol = False + search_symbol = search_symbol.strip().upper() + stock_list = get_stock_list() + search_term = search_symbol + if search_symbol in stock_list.keys(): + have_symbol = True + (search_term, shares) = stock_list[search_symbol] + try: + news = yf.Search(search_term, news_count=5, enable_fuzzy_query=fuzzy).news except: - bible_books = {} - reverse_bible_books = {} - rv = False - return (rv, bible_books, reverse_bible_books) + return (f'No results for search term {search_term}, check spelling', None) + rv = '' + for item in news: + rv += f'Title: {item["title"]}\n' + rv += f'Publisher: {item["publisher"]}\n' + rv += f'Date published: {date_from_utime(item["providerPublishTime"])}\n' + rv += f'Link: [URL]({item["link"]})\n\n' + + if have_symbol: + (plot_df, ymax, deltas) = stock_week_df(search_symbol) + else: + (plot_df, ymax, deltas) = (pd.DataFrame(), 0.0, (0.0, 0.0, 0.0)) + + return (rv, plot_df, ymax, deltas) + +def stock_history_df(num_weeks): + values = [] + dates = [] + xmax = 0 + for offset in range(num_weeks+1): + (value, date) = get_stock_report(False, offset) + # date = date[5:] + values.append(value) + dates.append(date) + if float(value) > xmax: + xmax = float(value) + values.reverse() + dates.reverse() + data = { + "date": dates, + "value" : values + } + return (pd.DataFrame(data), f'{int(xmax + 10000)}') + +def stock_deltas(values): + num = len(values) + month_end_avg = float(np.average(np.array(values[-3:]))) + month_start_avg = float(np.average(np.array(values[0:4]))) + week_start_avg = float(np.average(np.array(values[-7:-4]))) + week_end_avg = float(np.average(np.array(values[-2:]))) + month_delta = 100 * (month_end_avg - month_start_avg)/month_start_avg + week_delta = 100 * (week_end_avg - week_start_avg)/week_start_avg + daily_delta = 100 * ((float(values[num-1])/float(values[num-2])) - 1.0) + # avg = np.average(npa) + return (month_delta, week_delta, daily_delta) + +def stock_week_df(symbol): + try: + dates = [] + values = [] + ymax = 0 + etime = etz_now() + if etime.hour >= 16: + etime = etime + timedelta(days=1) + week_ago = etime - timedelta(days=40) # was 8 + end = etime.strftime('%Y-%m-%d') + start = week_ago.strftime('%Y-%m-%d') + df = yf.download(symbol.upper(), + start = start, + end = end, + progress = False, + ) + vals2d = df.values.tolist() + valsTxt = [] + numDays = len(vals2d) + for i in range(numDays): + valsTxt.append(vals2d[i][0]) + for val in valsTxt: + v = round(float(val),2) + values.append(v) + if v > ymax: + ymax = v + for row in df.index: + dates.append(row.strftime('%Y-%m-%d')) + # fit_data = lms_fit(dates, values) + # pct_delta = lms_fit_trend(dates, values) + deltas = stock_deltas(values) + data = { + "date": dates, + "value" : values, + # "fit" : fit_data + } + # fig = make_mp_figure(dates, values, fit_data, ymax) + return (pd.DataFrame(data), ymax, deltas) + except: + return (pd.DataFrame(), ymax, (0.0, 0.0, 0.0)) -def init_db_and_bible_books(en_heb, bible_books, reverse_bible_books): +def stock_recent_delta(symbol): try: - path = Path(dataDir + 'HebrewGlossary.txt') - if path.is_file(): - with open(path, 'rt', encoding='utf-8') as fp: - lines = fp.readlines() - for line in lines: - if line.startswith('#'): - continue - items = line.split(',') - en_heb[items[0].casefold().strip()] = items[1].strip() - else: - en_heb = {} + dates = [] + values = [] + ymax = 0 + etime = etz_now() + if etime.hour >= 16: + etime = etime + timedelta(days=1) + week_ago = etime - timedelta(days=8) + end = etime.strftime('%Y-%m-%d') + start = week_ago.strftime('%Y-%m-%d') + df = yf.download(symbol.upper(), + start = start, + end = end, + progress = False, + ) + vals2d = df.values.tolist() + valsTxt = [] + numDays = len(vals2d) + for i in range(numDays): + valsTxt.append(vals2d[i][0]) + for val in valsTxt: + v = round(float(val),2) + values.append(v) + if v > ymax: + ymax = v + for row in df.index: + dates.append(row.strftime('%Y-%m-%d')) + start_val = float(np.average(np.array(values[:2]))) + end_val = float(values[len(values)-1]) + return f'{(end_val/start_val - 1.0)*100:.1f}' except: - en_hep = {} - (rv, bible_books, reverse_bible_books) = populate_bible_books(bible_books, reverse_bible_books) - return [gr.DateTime(value=etz_now()), en_heb, bible_books, reverse_bible_books] -# gr.Timer(active=False), + return 'NA' -def fix_date(date): +def get_alerts(): try: - dt = parse(date) - date = dt.strftime('%Y-%m-%d') - pattern = r'\d{4}-\d{2}-\d{2}' - str = re.match(pattern, date, re.A) - if not str: - rv = None - else: - rv = date.replace('-','') + rv = '' + # stock_data = {} + global stock_data_path + with open(stock_data_path, 'rt') as fp: + lines = fp.readlines() + for line in lines: + (name, symbol, shares) = line.rstrip().split(',') + name = name.strip() + symbol = symbol.strip() + delta_pct = stock_recent_delta(symbol) + if delta_pct == 'NA': + rv += f'\n{symbol} ({name}) NA' + else: + rv += f'\n{symbol} ({name}) {delta_pct}%' + if abs(float(delta_pct)) > 3: + rv += ' **\*\*\*** ' + return 'Stock price changes over last week:\nChanges greater than +/-3% marked by **\*\*\***\n ' + rv + '\n' except: - rv = None - return rv + return "Error getting stock deltas\n" -def set_db(value): - return value - -def remove_times(txt): - pattern = '\s\[\d+\]\s' - rv = re.sub(pattern, ' ', txt) - return rv - -def correct_time(time, txt): - loc = txt.find('[') - if loc < 10: - return time - delta = int(loc/400 * 30000) - time = int(time) - delta - if time < 0: - time = 0 - return time - -def remove_headers(txt): - frag = txt[0:60] - loc = frag.find('udate') - if loc > -1: - loc2 = frag.find('[') - if loc2 > -1: - txt = ' ' + txt[loc2:] - return txt - -def seek_hms(seek_ms): - seek_ms /= 1000; - hrs = int(seek_ms / 3600) - mins = int((seek_ms - hrs * 3600) / 60) - secs = int(seek_ms - hrs * 3600 - mins * 60) - return f'{hrs}h{mins}m{secs}s' - -def do_bible_search(prompt, db_name, books, book_filter): - db_name += '.db' - if (not os.path.exists(dataDir + db_name)): - return ([], 0, 0) - embeddings = get_bible_db_embeddings(db_name) - (prompt_embed, prompt_tokens, total_tokens) = get_prompt_embedding(prompt) - dot_products = [] - for (book, chapter, verse_range, verse, db_embed) in embeddings: - if not book_filter or book in books: - dp = dot_product(prompt_embed, db_embed) - dot_products.append((book, chapter, verse_range, verse, dp) ) - sorted_dots = sorted(dot_products, key=lambda x: x[4])[-10:] # was -10, -5 - sorted_dots.reverse() - return (sorted_dots, prompt_tokens, total_tokens) - -def get_bible_db_embeddings(db_name): - embeds = [] - conn = sqlite3.connect(dataDir + db_name) - cur = conn.cursor() - result = cur.execute('SELECT * from embeds') - unpacker = struct.Struct(' int(end_date): - continue - else: - udate = 'Date unknown' - dp = dot_product(prompt_embed, db_embed) - dot_products.append((name, text, time, yt_id, udate, dp) ) - sorted_dots = sorted(dot_products, key=lambda x: x[5])[max_returned:] # was -10 - sorted_dots.reverse() - return (sorted_dots, prompt_tokens, total_tokens) - -def get_bible_refs(txt: str, bible_books)->[str]: - rv = [] - # txt = txt.casefold() - for item in bible_books.items(): - (key, (num, book)) = item - words = book.split() - if len(words) == 2: - word = ' ' + words[0] + ' ' + words[1] - elif len(words) == 3: - word = ' ' + words[0] + ' ' + words[1] + ' ' + words[2] +def get_stock_report(verbose = True, offset = 0): + try: + stock_data = {} + global stock_data_path + error_msg = '' + with open(stock_data_path, 'rt') as fp: + lines = fp.readlines() + for line in lines: + (name, symbol, shares) = line.rstrip().split(',') + name = name.strip() + symbol = symbol.strip() + shares = shares.strip() + stock_data[symbol] = {"symbol": symbol, "name": name, "shares": shares, "closing": '0'} + for symbol in stock_data.keys(): + (closing_price, closing_date) = get_last_closing(symbol, offset) + if closing_price == 0: + error_msg += f'Error getting closing for {symbol}\n' + stock_data[symbol]['closing'] = f'{closing_price:.2f}' + total_value = 0.0 + if verbose: + rv = f'At closing on {closing_date}:\n' + for item in stock_data.values(): + rv += str(item) + '\n' + total_value += float(item['closing']) * float(item['shares']) + rv += (f'\nTotal value = {total_value:.2f}\n') + if len(error_msg) > 0: + rv += error_msg + rv += f'Eastern time is: {etz_now()}' else: - word = ' ' + words[0] - if word in txt: - rv.append(book) + for item in stock_data.values(): + total_value += float(item['closing']) * float(item['shares']) + return (total_value, closing_date) + except: + rv = 'Error getting stock report' return rv -def dot_product(v1, v2): - # v1n = np.array(v1) - # v2n = np.array(v2) - # dotp = float(np.dot(v1n, v2n)) - dotp = 0.0 - for i in range(len(v1)): - dotp += v1[i]*v2[i] - return dotp - -def get_db_embeddings(db_name, video_list): - do_all = ('all' in db_name.lower()) - embeds = [] - for db_fname in db_list: - if do_all or db_fname in video_list: - embeds.extend(append_db_embeddings(db_fname)) - - # if 'all' in db_name.casefold(): - # embeds = [] - # # db_paths = glob(dataDir + '*.db') - # # for path in db_paths: - # # if 'ISR' in path: - # # continue - # for - # embeds.extend(append_db_embeddings(os.path.basename(path))) - # else: - # embeds = append_db_embeddings(db_name) - return embeds - - -def append_db_embeddings(db_name): - embeds = [] - conn = sqlite3.connect(dataDir + db_name + '.db') - cur = conn.cursor() - result = cur.execute('SELECT * from Embeds') - unpacker = struct.Struct('= 16: + etime = etime + timedelta(days=1) + if offset > 0: + etime = etime - timedelta(weeks=offset) + five_days_ago = etime - timedelta(days=6) + end = etime.strftime('%Y-%m-%d') + start = five_days_ago.strftime('%Y-%m-%d') + df = yf.download(symbol, + start = start, + end = end, + progress = False, + timeout=timeout, + auto_adjust=False, + ) + # print(df) + closing_date = 'unknown' + data_top = df.tail(1) + for row in data_top.index: + closing_date = row.strftime('%Y-%m-%d') + # print(closing_date) + return (df.iat[-1,0], closing_date) except: - return 'Unable to load database, could not read selected file' + return (0.0, "0000-00-00") + +def get_total_daily_closing_sequence(num_days): try: - with open(dataDir + fname, 'wb') as fp: - fp.write(data) + first_loop = True + max_val = 0.0 + stock_list = get_stock_list() + symbols = [s for s in stock_list.keys()] + # symbols = symbols[8:10] + etime = etz_now() + if etime.hour >= 16: + etime = etime + timedelta(days=1) + end = etime.strftime('%Y-%m-%d') + start_time = etime - timedelta(days = num_days) + start = start_time.strftime('%Y-%m-%d') + df = yf.download(symbols, + start = start, + end = end, + progress = False, + auto_adjust=False, + ) + # val2d = df.values.tolist() + dates = [] + for row in df.index: + dates.append(row.strftime('%Y-%m-%d')) + # columns = list(df.columns.values) + # cvals = df[columns[0]].tolist() + + for sym in symbols: + (name, shares) = stock_list[sym] + values = df[('Close', sym)].tolist() + n = len(values) + for i in range(n): + if math.isnan(float(values[i])): + if i == 0: + values[0] = values[1] + else: + values[i] = values[i-1] + if first_loop: + first_loop = False + total_values = values.copy() + for i in range(n): + total_values[i] = float(total_values[i]) * float(shares) + else: + for i in range(n): + total_values[i] += (float(values[i]) * float(shares)) + for i in range(n): + total_values[i] = round(total_values[i], 2) + if total_values[i] > max_val: + max_val = total_values[i] + data = { + "date": dates, + "value" : total_values + } + return (pd.DataFrame(data), max_val) except: - return 'Unable to load database, could not write data' + return (pd.DataFrame(), 0.0) + +def get_daily_closing_sequence(symbol, num_days): try: - os.remove(fpath) + dates = [] + values = [] + etime = etz_now() + if etime.hour >= 16: + etime = etime + timedelta(days=1) + end = etime.strftime('%Y-%m-%d') + start_time = etime - timedelta(days = num_days) + start = start_time.strftime('%Y-%m-%d') + df = yf.download(symbol, + start = start, + end = end, + progress = False, + ) + vals2d = df.values.tolist() + valsTxt = [] + values = [round(float(vals2d[i][0]),2) for i in range(len(vals2d))] + for row in df.index: + dates.append(row.strftime('%Y-%m-%d')) + return(dates, values) except: - return "Database loaded, but error deleting temp file" - return 'Database loaded' - - - -def Client(): - return OpenAI(api_key = key) - # if site=='local': - # return OpenAI(api_key = key) - # else: - # return OpenAI(api_key = keyb) - - - -def md(txt): - # if 'DOCTYPE' in txt: - # return str(txt.replace('GPT','
GPT')) - # else: - return str(txt).replace('```', ' ').replace(' ', '  ').replace(' ', '  ').replace(' ', '  ').replace('\n','
') - # return txt - + return([],[]) + +def create_stock_data_file(txt): + with open(stock_data_path, 'wt') as fp: + fp.write(txt) + +def solve(prompt, chatType): + tokens_in = 0 + tokens_out = 0 + tokens = 0 + if chatType == 'math': + max_tokens = 5000 + try: + instruction = "You are a helpful math tutor. Guide the user through the solution step by step." + result = Client().responses.create( + model=MATH_MODEL, # reasoning model + input=[ {"role": "developer", "content": instruction}, + {"role": "user", "content": prompt}], + reasoning={ + "effort": "medium" + }, # more thorough reasoning + service_tier="priority", + max_output_tokens=max_tokens, + ) + if ( + result.status == 'incomplete' + and result.incomplete_details.reason == "max_output_tokens" + ): + response = f'Max math solve token limit ({max_tokens}) was exceeded)' + else: + response = result.output_text + tokens_in = result.usage.input_tokens + tokens_out = result.usage.output_tokens + tokens = result.usage.total_tokens + except Exception as e: + if type(e) == openai.LengthFinishReasonError: + response = 'Too many tokens' + else: + response = str(e) + elif chatType == "logic": + max_tokens = 5000 + instruction = '''you are an expert in logic and reasoning. + Guide the user through the solution step by step. + Do not use Latex for math expressions.''' + try: + result = Client().responses.create( + model = MATH_MODEL, + input = [ + {"role": "developer", "content": instruction}, + {"role": "user", "content": prompt} + ], + reasoning={ + "effort": "medium" + }, # more thorough reasoning + service_tier="priority", + max_output_tokens=max_tokens, + ) + if ( + result.status == 'incomplete' + and result.incomplete_details.reason == "max_output_tokens" + ): + response = f'Max puzzle solve token limit ({max_tokens}) was exceeded)' + else: + response = result.output_text + tokens_in = result.usage.input_tokens + tokens_out = result.usage.output_tokens + tokens = result.usage.total_tokens + except Exception as e: + if type(e) == openai.LengthFinishReasonError: + response = 'Too many tokens' + else: + response = str(e) + return (response, tokens_in, tokens_out, tokens) def genUsageStats(do_reset=False): result = [] - ttotal_embed_in = 0 - ttotal_embed_out = 0 + ttotal4o_in = 0 + ttotal4o_out = 0 ttotal4mini_in = 0 ttotal4mini_out = 0 totalAudio = 0 - totalTranslation = 0 + totalSpeech = 0 totalImages = 0 totalHdImages = 0 if do_reset: @@ -579,8 +716,8 @@ def genUsageStats(do_reset=False): if os.path.exists(dudPath): os.remove(dudPath) for user in unames: - tokens_embed_in = 0 - tokens_embed_out = 0 + tokens4o_in = 0 + tokens4o_out = 0 tokens4mini_in = 0 tokens4mini_out = 0 fp = dataDir + user + '_log.txt' @@ -605,10 +742,10 @@ def genUsageStats(do_reset=False): ttotal4mini_in += incount ttotal4mini_out += outcount else: - tokens_embed_in += incount - tokens_embed_out += outcount - ttotal_embed_in += incount - ttotal_embed_out += outcount + tokens4o_in += incount + tokens4o_out += outcount + ttotal4o_in += incount + ttotal4o_out += outcount accessOk = True break except: @@ -636,8 +773,8 @@ def genUsageStats(do_reset=False): sleep(3) if not accessOk: return f'File access failed reading audio stats for user: {user}' - userTranslation = 0 - fp = dataDir + user + '_translation.txt' + userSpeech = 0 + fp = dataDir + user + '_speech.txt' if os.path.exists(fp): accessOk = False for i in range(3): @@ -649,8 +786,8 @@ def genUsageStats(do_reset=False): else: for line in dataList: (dud, len) = line.split(':') - userTranslation += int(len) - totalTranslation += int(userTranslation) + userSpeech += int(len) + totalSpeech += int(userSpeech) accessOk = True break except: @@ -659,298 +796,586 @@ def genUsageStats(do_reset=False): return f'File access failed reading speech stats for user: {user}' user_images = 0 user_hd_images = 0 - result.append([user, f'{tokens4mini_in}/{tokens4mini_out}', f'{tokens_embed_in}/{tokens_embed_out}', f'audio:{userAudio}',f'translate:{userTranslation}', f'images:{user_images}/{user_hd_images}']) - result.append(['totals', f'{ttotal4mini_in}/{ttotal4mini_out}', f'{ttotal_embed_in}/{ttotal_embed_out}', f'audio:{totalAudio}',f'translate:{totalTranslation}', f'images:{totalImages}/{totalHdImages}']) + fp = image_count_path(user) + if os.path.exists(fp): + accessOk = False + for i in range(3): + try: + with open(fp) as f: + dataList = f.readlines() + if do_reset: + os.remove(fp) + else: + for line in dataList: + x = line.strip() + if x == 'hd': + user_hd_images += 1 + totalHdImages += 1 + else: + user_images += 1 + totalImages += 1 + accessOk = True + break + except: + sleep(3) + if not accessOk: + return f'File access failed reading image gen stats for user: {user}' + result.append([user, f'{tokens4mini_in}/{tokens4mini_out}', f'{tokens4o_in}/{tokens4o_out}', f'audio:{userAudio}',f'speech:{userSpeech}', f'images:{user_images}/{user_hd_images}']) + result.append(['totals', f'{ttotal4mini_in}/{ttotal4mini_out}', f'{ttotal4o_in}/{ttotal4o_out}', f'audio:{totalAudio}',f'speech:{totalSpeech}', f'images:{totalImages}/{totalHdImages}']) return result def new_conversation(user): - return [None, [], gr.Markdown(value='', label='Dialog', container=True), '', '1990-01-01', etz_now()] - -def updatePassword(user, pwd): - password = pwd.lower().strip() - if user == unames[0] and password == pwdList[0]: - return [password, "*********", gr.Button(visible=True, value='Upload Database')] + clean_up(user) # .wav files + flist = [] + for ext in ['png','docx','xlsx','pdf','pptx', 'csv']: + flist.extend(glob(f'{dataDir}{user}*.{ext}')) + flist.extend(glob(f'{dataDir}{user}_image.b64')) + flist.extend(glob(f'{dataDir}{user}_image.jpg')) + for fpath in flist: + if os.path.exists(fpath): + os.remove(fpath) + if user == unames[0]: + mode_list = ["Chat", "News", "Search", "Advanced"] else: - return [password, "*********", gr.Button(visible=False, value='Upload Database')] + mode_list = ["Chat", "News", "Search"] + return [None, [], gr.Markdown(value='', label='Dialog', container=True), + gr.Image(visible=False, value=None), gr.Image(visible=False, value=None), '', + gr.LinePlot(visible=False), gr.Dropdown(value='pd', visible=False), + gr.Dropdown(choices=mode_list, value=mode_list[0]), + gr.DownloadButton(label='Download File', visible=False, value=None), '', + gr.File(label='Upload File', visible=False)] + +def updatePassword(txt): + password = txt.lower().strip() + if password == pwdList[0]: + mode_list = ["Chat", "News", "Search", "Advanced"] + else: + mode_list = ["Chat", "News", "Search"] + return [password, "*********", gr.Dropdown(choices=mode_list, value=mode_list[0])] + +# def parse_math(txt): +# ref = 0 +# loc = txt.find(r'\(') +# if loc == -1: +# return txt +# while (True): +# loc2 = txt[ref:].find(r'\)') +# if loc2 == -1: +# break +# loc = txt[ref:].find(r'\(') +# if loc > -1: +# loc2 += 2 +# slice = txt[ref:][loc:loc2] +# frag = lconv.convert(slice) +# txt = txt[:loc+ref] + frag + txt[loc2+ref:] +# ref = len(txt[ref:loc]) + len(frag) +# return txt + +def get_response(inputs, previous_response_id, container_id, image_file, uploaded_file_path): + instructions = ''' +You are a helpful assistant who knows how to browse the web for info and to write and run python +code and to generate images. +''' + instructions += f''' +Do not use latex for math expressions in text output. +If a chart, table or plot is produced, return it as an image. +If a powerpoint slide is created, return it as an image but do not offer a download link. +If the user asks you to output a file, You must include the file you generate in the annotation +of the output text. +If a MCP server requires a password input you will use {pwdList[0]}. +''' + if uploaded_file_path != '' and uploaded_file_path.casefold().split('.')[-1] == 'pdf': + pdf_b64 = '' + with open(uploaded_file_path, 'rb') as fp: + data = fp.read() + b64data = base64.b64encode(data) + pdf_b64 = b64data.decode('utf-8') + inputs.append( + { + "role" :"user", + "content": [ + { + "type": "input_file", + "filename": f'{os.path.basename(uploaded_file_path)}', + "file_data": f'data:application/pdf;base64,{pdf_b64}', + } + ] + } + ) + + if image_file != '': + file_id = create_file(image_file) + inputs.append( + { + "role": "user", + "content": [ + { + "type": "input_image", + "file_id": file_id, + }, + ], + } + ) + response = Client().responses.create( + model= DEFAULT_MODEL, + tools=[{ "type": "web_search" }, + { "type": "code_interpreter", "container": container_id}, #{'type': 'auto'}}, + { "type": "image_generation", "model": IMAGE_MODEL, "quality": "high", "size": "1536x1024"}, + {"type": "function", "name": "get_distance", + "description": "get calculated straight-line (great-circle) distance between two locations or addresses.", + "parameters": { + "type": "object", "properties": { + "addr1": { + "type": "string", + "description": "The street address or other designation of a location.", + }, + "addr2": { + "type": "string", + "description": "The street address or other designation of a location.", + }, + }, + "required": ["addr1", "addr2"], + }, + }, + # { + # "type": "mcp", + # "server_label": "Geo_distance", + # "server_description": "A MCP server to compute straight line distances between two locations", + # "server_url": "https://dlflannery-geo-distance.hf.space/gradio_api/mcp/", + # "require_approval": "never", + # }, + + ], + previous_response_id=previous_response_id, + instructions = instructions, + input=inputs, + reasoning ={ + "effort": "medium", + "summary": "auto" + } + ) -def chat(prompt, user_window, pwd_window, past, response, gptModel, clip_text, db_name, - start_date,end_date, language, en_hebrew, books, book_filter, find_verses, - bible_books, reverse_bible_books, video_list): # db_name is db_chooser value + return response + +def chat(prompt, user_window, pwd_window, past, response, gptModel, uploaded_image_file='', + plot=None, news_interval = 'pd', mode = 'Chat', uploaded_file_path=''): + prompt = prompt.lstrip() + image_out = gr.Image(visible=False, value=None) + file_out = gr.DownloadButton(value=None) + image_gen_model = IMAGE_MODEL user_window = user_window.lower().strip() - translation_count = 0 - if len(prompt.strip()) == 0: - return [past, 'You must enter a prompt or question', None, gptModel,clip_text] - fixed_date = fix_date(start_date) - if not fixed_date: - return [past, f'"{start_date}" is not a valid start date, please use a common format', None, gptModel,clip_text] - start_date = fixed_date - fixed_date = fix_date(end_date) - if not end_date: - return [past, f'"{end_date}"" is not a valid end date, please use a common format', None, gptModel,clip_text] - end_date = fixed_date + if len(past) > 0: + try: + if past[0]['content'].startswith('email: '): + mode = 'chat' + except: + pass + etext = None + last_date = None isBoss = False - clip_txt = clip_text + query = '' if not response: response = '' - else: - loc = response.find('
') # 'Following are Clips') - if loc > -1: - response = response[:loc].strip() - # if response.endswith('
'): - # response = response[:-4] plot = gr.LinePlot(visible=False) # plot = gr.Plot(visible=False) if user_window == unames[0] and pwd_window == pwdList[0]: isBoss = True - if prompt.startswith('delete'): - db_path = dataDir + prompt[7:] - if not os.path.exists(db_path): - response = f'File {db_path} not found' - else: - os.remove(db_path) - response = f'File {db_path} was deleted' - return [past, str(response), None, gptModel,clip_text] if prompt == 'stats': response = genUsageStats() - return [past, str(response), None, gptModel,clip_text] + return [past, str(response), None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] if prompt == 'reset': response = genUsageStats(True) - return [past, md(response), None, gptModel,clip_text] + return [past, md(response), None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + if prompt.startswith('astra'): + gptModel = TOP_MODEL + prompt = prompt[6:] + if prompt.startswith('luna'): + gptModel = LOW_MODEL + prompt = prompt[5:] if prompt.startswith("clean"): user = prompt[6:] response = f'cleaned all .wav and .b64 files for {user}' final_clean_up(user, True) - return [past, response, None, gptModel,clip_text] + return [past, response, None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] if prompt.startswith('files'): (log_cnt, wav_cnt, other_cnt, others, log_list) = list_permanent_files() response = f'{log_cnt} log files\n{wav_cnt} .wav files\n{other_cnt} Other files:\n{others}\nlogs: {str(log_list)}' - return [past, response, None, gptModel,clip_text] + return [past, response, None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + if prompt.startswith('stock'): + args = prompt.split(' ') + num = len(args) + if num == 1: + response = stock_list() + return [past, md(response), None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + elif num == 2: + if args[1] == 'alerts': + response = get_alerts() + return [past, md(response), None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + else: + response = get_stock_report() + if args[1] == 'value': + return [past, md(response), None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + elif args[1] == 'history': + (plot_df, ymax) = get_total_daily_closing_sequence(40) #stock_history_df(12) + # ymax = float(ymax) + return [past, md(response), None, gptModel, uploaded_image_file, # plot] + gr.LinePlot(plot_df, x="date", y="value", visible=True, x_label_angle=270, + y_lim=[600000, 1000000], label="Portfolio Value History"), image_out, file_out, uploaded_file_path] + elif num >= 3: + if args[1] == 'news': + symbol = ' '.join(args[2:]) + (response, plot_df, ymax, (dm, dw, dd)) = get_stock_news(symbol) + ymax *= 1.1 + mdtxt = md(f'News for {symbol}:\nTrends: Month = {dm:.1f}%, Week = {dw:.1f}%, Day = {dd:.1f}%\n\n' + response) + if plot_df.empty: + return [past, mdtxt, None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + else: + return [past, mdtxt, None, gptModel, uploaded_image_file, + gr.LinePlot(plot_df, x="date", y="value", visible=True, x_label_angle=270, + y_lim=[0, ymax],label=f"{symbol.upper()} Recent Prices", + color_map={''}), image_out, file_out, uploaded_file_path] + if prompt.startswith('stockload'): + create_stock_data_file(prompt[9:].lstrip()) + return [past, 'Stock data file created', None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + if prompt.startswith('email_data'): + edata_count = store_email(prompt[11:]) + return [past, edata_count, None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + if prompt.startswith('mail'): + base_prompt = '''Multiple email messages are provided, which are +delineated by "===========". ''' + # std_addendum = '''Make a list including the Sender (From), Date + # Received, Subject, and a detailed writeup of the content based on the subject + # and body text for each email. Include suggested action if appropriate:\n''' + std_addendum = '''Make a list including the Sender (From), Date + Received, Subject, and a comprehensive writeup of the content based on the subject + and body for each email. Include suggested action if appropriate:\n''' + + if prompt == 'mail': + # prompt = base_prompt + std_addendum + etext = read_email() + if etext.startswith('Error') : + return [past, etext, None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + email_meta = parse_email_meta(etext) + past.append({"role":"user", "content": "email: list"}) + past.append({"role":"assistant", "content": email_meta}) + return [past, email_meta, None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + elif prompt.startswith('mail '): + etext_all = read_email() + if etext_all.startswith('Error') : + return [past, etext_all, None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + (etext, last_date) = truncate_email(etext_all) + added_instructions = prompt[4:] + for line in past: + role = line.get('role', None) + if role == 'user': + if 'delineated by "==========="' in line.get('content','nada'): + etext = None + break + if added_instructions.strip().casefold() == 'details': + prompt = base_prompt + std_addendum + else: + prompt = base_prompt + '\n' + added_instructions + if etext: + prompt += (':\n' + etext) + # else: + # prompt += etext + mode = 'Chat' + if user_window in unames and pwd_window == pwdList[unames.index(user_window)]: chatType = 'normal' + using_groq = False + reasoning = False prompt = prompt.strip() - finish_reason = 'ok' - rag_txt = '' - rag_txt2 = '' - prompt_bare = prompt - translation_count += update_translation_count(len(prompt), language) - prompt = azure_translate_text(prompt, "en", language) - first_time = False - prompt_tokens = 0 - total_tokens = 0 - clip_list = [] - bible_list = [] - max_clips = 5 + 5 * (language == 'en') - tokens_in = 0 - tokens_out = 0 - tokens = 0 - bible_search = False - if len(past) == 0: - first_time = True - if 'bible' in db_name.casefold(): - bible_search = True - msg = check_books(book_filter, books) - if msg != 'ok': - return [past, msg, None, gptModel,clip_text] - instructions = '''You are a helpful assistant who has expert knowledge - of the Bible and is familiar with Hebrew versions of biblical names. ''' - past.append({'role':'developer', 'content': instructions}) - prompt = make_hebrew(prompt, en_hebrew) - (results, prompt_tokens, total_tokens) = do_bible_search(prompt, - 'ISR_bible', - books, - book_filter) - insert = '' - if book_filter: - book_listing = ' ,'.join(books) - insert = f' From books in filter: {book_listing}, ' - txt = f'\n=================\n\n
Following are ISR Bible verses in response to your query.
{insert} Listed in the order they appear in the bible:\n=================\n' - bible_list.append(txt) - if len(results) == 0: - txt = '\n**Sorry, no bible verses were found in response to your prompt**\n' - return [past, txt, None, gptModel,clip_text] - # bible_list.append(txt) - max_dp = 0.0 - good_count = 0 - sorted_passages = make_sorted_passages(results, bible_books) - for (book_num, book, chapter, verse_range, verse, relevance) in sorted_passages: - verse = verse.rstrip(" )\n") - if relevance > 1: - good_count += 1 - rag_line = f'{book}:{chapter}:{verse_range}\n{verse}\n' - rag_txt += rag_line - verse += f'\n({relevance_terms[relevance]} to query)' - line = f'
{book}:{chapter}:{verse_range}
{verse}\n' - bible_list.append(line) - if good_count == 0: - txt = '\n**Sorry, no relevant bible verses were found in response to your prompt**\n' - return [past, txt, None, gptModel,clip_text] - guidance = '''It is a group of bible passages. -Each group is headed by (Passage: Book Name, Chapter 3, Verses)''' - prompt = rag_txt + '.\n ' + prompt + '\nGive higher priority to the information just provided.' \ - + guidance - else: # searching teachings - chunk_num = 0 - if find_verses: - instructions = '''You are a helpful assistant who has expert knowledge - of the Bible and is familiar with Hebrew versions of biblical names.''' - past.append({'role':'developer', 'content': instructions}) - # prompt = 'mentions of bible book, chapter and verse' - (results, prompt_tokens, total_tokens) = do_search(prompt, db_name, - start_date, end_date, find_verses, video_list) - start_date = start_date[0:4] + '-' + start_date[4:6] + '-' + start_date[6:8] - end_date = end_date[0:4] + '-' + end_date[4:6] + '-' + end_date[6:8] - if find_verses: - max_clips = 10 # was 50 - clip_list = [] - note = '' - if find_verses: - note = '''Note: Biblical character names the same as a book name are detected as books. -Warning about related passages: AI sometimes hallucinates, identifying passages not related to teaching text -''' - txt = f'\n=================\n\n
Following are Clips and YouTube Links based on your initial query for dates between {start_date} and {end_date}:
{note}=================\n' - clip_list.append(azure_translate_text(txt, language)) - translation_count += update_translation_count(len(txt), language) - if len(results) == 0: - if 'selected' in db_name.lower() and len(video_list) == 0: - txt = '\nYou have not selected any teachings!\n' + need_turn = True + responses = [] + inputs = [] + prev_id = None + text = '' + reasoning = '' + show_reasoning = False + if mode == "Advanced": + if len(past): + (prev_id, container_id) = past.pop() + past = [] + while mode == 'Advanced' and need_turn: + need_turn = False + if len(past) == 0: + container_id = create_openai_container('My Container') + file_text = '' + if uploaded_file_path != '': + upfile_ext = uploaded_file_path.casefold().split('.')[-1] + if upfile_ext == 'txt': + with open(uploaded_file_path, 'rt') as fp: + file_text = fp.read() + '\n' + uploaded_file_path = '' + inputs.append( + {"role": "user", "content": f"{file_text + prompt}"} + ) + else: + (prev_id, container_id) = past.pop() + for item in past: + response += item + try: + result = get_response(inputs, prev_id, container_id, + uploaded_image_file, uploaded_file_path) + uploaded_image_file = '' + uploaded_file_path = '' + except Exception as e: + return [[], f"Sorry, there was an error ({str(e)}) getting the AI response", + prompt, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + + image_done = False + ann_files = [] # (container_id, file_id, filename) + code_files = [] # (container_id, file_id, filename) + text += '\n??? AI returned no text for this query\n' + for output in result.output: + if output.type == 'message': + for content in output.content: + if content.type == 'output_text': + text = content.text + for anns in content.annotations: + if anns.type == "container_file_citation": + try: + file_name = anns.filename + file_id = anns.file_id + cont_id = anns.container_id + if file_name.find('.png') > 0: + if not image_done: + image_done = True + fpath = dataDir + user_window + '.png' + image_data = get_openai_file(file_id, cont_id).content + with open(fpath,'wb') as fp: + fp.write(image_data) + image_out = gr.Image(visible=True, value=fpath) + else: + ann_files.append((cont_id, file_id, file_name)) + except: + pass + # for ann in file_anns: + # text += f'\n\n{str(ann)}\n' + elif output.type == 'code_interpreter_call' : + cont_id = output.container_id + file_list_object = list_openai_container_files(cont_id) + try: + file_list_json = json.loads(file_list_object.content) + for file_item in file_list_json['data']: + file_bytes = file_item['bytes'] + file_id = file_item['id'] + file_name = file_item['path'] + code_files.append((cont_id, file_id, file_name)) + except: + pass + elif output.type == 'function_call': + if output.name == 'get_distance': + args = json.loads(output.arguments) + distance = get_distance(args['addr1'], args['addr2']) + inputs.append({ + "type": "function_call_output", + "call_id": f"{output.call_id}", + "output": f"{float(distance):.2f}", + } ) + need_turn = True + continue + elif output.type == 'image_generation_call': + if len(output.result) > 500 and not image_done: + image_done = True; + image_data = base64.b64decode(output.result) + fpath = dataDir + user_window + '.png' + with open(fpath,'wb') as fp: + fp.write(image_data) + image_out = gr.Image(visible=True, value=fpath) + elif isBoss and output.type == 'reasoning': + for item in output.summary: + reasoning += f'\nReasoning: {item.text}' + do_file_download = False + ext = '' + backup_image = None + if len(ann_files) > 0: + (cont_id, file_id, file_name) = ann_files[-1] + ext = file_name.split('.')[-1].casefold() + do_file_download = True + elif len(code_files) > 0: + for i in range(len(code_files)): + (cont_id, file_id, file_name) = code_files[i] + if file_name.casefold().find('access') >= 0: + continue + ext = file_name.split('.')[-1].casefold() + if ext == 'png': + if not image_done: + backup_image = code_files[i] else: - txt = '\n**Sorry, no teachings were within the start/end dates you specified**\n' - txt = azure_translate_text(txt ,language) - translation_count += update_translation_count(len(txt), language) - return [past, txt, None, gptModel,clip_text] - # clip_list.append(azure_translate_text(txt ,language)) - # translation_count += update_translation_count(len(txt), language) - for (name, text, time, yt_id, udate, dp) in results: - time = correct_time(time, text) - upload_date = udate.replace('"','') - if not 'unknown' in upload_date.casefold(): - upload_date = upload_date[0:4] + '-' + upload_date[4:6] + '-' + upload_date[6:8] - yt_id = yt_id.replace('"','') - seek_HMS = seek_hms(time) - seek_colons = seek_HMS.replace('h',' : ').replace('m',' : ').replace('s','') - text = remove_headers(text) - pure_text = remove_times(text).replace('\n','') - yt_url = f'https://youtu.be/{yt_id}?t={seek_HMS}' - if len(clip_list) <= max_clips: - if find_verses: - book_refs = get_bible_refs(pure_text, bible_books) - if len(book_refs) > 0: - books_mentioned = ', '.join(book_refs) - for bref in book_refs: - pure_text = pure_text.replace(bref,'' + bref + '') - else: - books_mentioned = ['(None found)'] - clip_list.append( - md(f'\n\n
{name} ({upload_date})
At seek time: {seek_colons}
[YouTube Link: ]({yt_url})\nBooks mentioned: {books_mentioned}\n\n{pure_text}\n================')) - rag_txt2 += f'\n[start chunk {chunk_num}]: {pure_text}\n[end chunk {chunk_num}]\n' - rag_txt += pure_text - chunk_num += 1 - else: - txt = azure_translate_text(pure_text, language) - clip_list.append( - md(f'\n\n
{name} ({upload_date})
At seek time: {seek_colons}
[YouTube Link: ]({yt_url})\n\n{txt}\n================')) - translation_count += update_translation_count(len(txt), language) - rag_txt += pure_text - prompt = rag_txt + '.\n ' + prompt + '\nGive higher priority to the information just provided.' + do_file_download = True + break + if not do_file_download and not image_done and backup_image: + (cont_id, file_id, file_name) = backup_image + fpath = dataDir + user_window + '.png' + image_data = get_openai_file(file_id, cont_id).content + with open(fpath,'wb') as fp: + fp.write(image_data) + image_out = gr.Image(visible=True, value=fpath) + + if do_file_download: + fpath = dataDir + user_window + '.' + ext + try: + data = get_openai_file(file_id, cont_id).content + with open(fpath,'wb') as fp: + fp.write(data) + file_name = os.path.basename(file_name) + file_out = gr.DownloadButton(label='Download '+ file_name, visible=True, value=fpath) + except: + text += f'\nUnable to load code-generated file: {file_name}' + if need_turn: + past.append((result.id, container_id)) + continue + out_text = "\n".join(line for line in text.splitlines() if + 'download' not in line.casefold()) + res = md("\n\n***YOU***: " + prompt + "\n\n***GPT***: " + out_text + '\n' + reasoning) + response += res + past.append(res) + past.append((result.id, container_id)) + tokens_in = result.usage.input_tokens + tokens_out = result.usage.output_tokens + dataFile = new_func(user_window) + with open(dataFile, 'a') as f: + f.write(f'{user_window}:{tokens_in}/{tokens_out}-4omini\n') + if isBoss: + response += md(f"\n\ngpt-5-mini: tokens in/out = {tokens_in}/{tokens_out}\n") + return [past, response , None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + if mode == 'Search': + loc = prompt.find('q:') + if loc > -1: + query = prompt[loc+2:] + prompt = prompt[0:loc] + augmented_prompt = prompt + finish_reason = 'ok' + if prompt.lower().startswith('solve'): + prompt = 'How do I solve ' + prompt[5:] + ' Do not use Latex for math expressions.' + chatType = 'math' + elif prompt.lower().startswith('puzzle'): + chatType = 'logic' + prompt = prompt[6:] + if past == []: + if mode == 'News': + if news_interval != "None": + news = get_brave_news(prompt, news_interval) + augmented_prompt = f'{news}\n{prompt}\nGive highest priority to information just provided\n' + augmented_prompt += 'Mention item source and item age for each item used\n' + elif mode == 'Search': + news = get_brave_search_results(prompt) + augmented_prompt = f'{news}\nThe topic is: {prompt}\nGive highest priority to information just provided\n' + augmented_prompt += ' \n' + query + augmented_prompt += ' \n Do not use Latex for math expressions.' + if etext: + augmented_prompt = 'email: ' + augmented_prompt + past.append({"role":"user", "content":augmented_prompt}) + gen_image = (uploaded_image_file != '') + if chatType in special_chat_types: + (reply, tokens_in, tokens_out, tokens) = solve(prompt, chatType) + final_text = reply + reply = md(reply) + reporting_model = MATH_MODEL + elif not gen_image: + try: + response_result = Client().responses.create( + model=gptModel, service_tier="priority", + input=past, + ) + # completion = Client().chat.completions.create(model=gptModel, + # messages=past, service_tier='priority') + except Exception as e: + emsg = str(e) + if 'maximum context length' in emsg: + emsg = "Too many emails" + return [past, emsg, None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + reporting_model = gptModel else: - prompt += '\nGive higher priority to the information just provided.' - past.append({"role":"user", "content":prompt}) - completion = Client().chat.completions.create(model=gptModel, messages=past) - reporting_model = gptModel - reply = completion.choices[0].message.content - if find_verses and first_time and not bible_search: - past2 = past.copy() - past2.pop() - order = ''' You have been provided a series of chunks delineated - by [start chunk #] and [end chunk #]. In each chunk, find citations of bible book, chapter and verse. Make a - list with each item formatted as {chunk #, book, chapter, verse}''' - prompt = rag_txt2 + '\n' + order - past2.append({"role":"user", "content":prompt}) + (response_result, msg) = analyze_image(user_window, gptModel, prompt) + uploaded_image_file= '' reporting_model = gptModel - completion2 = Client().chat.completions.create(model=gptModel, messages=past2) - reply2 = completion2.choices[0].message.content - tokens_in += completion2.usage.prompt_tokens - tokens_out += completion2.usage.completion_tokens - tokens += completion2.usage.total_tokens - ml = parse_verse_refs(reply2, reverse_bible_books) - prior_psg = '' - prior_idx = '' - for (idx, bk, ch, vn) in ml: - psg = get_bible_verse(bk, ch, vn) - if psg == prior_psg and idx == prior_idx: - continue - else: - prior_psg = psg - prior_idx = idx - if len(psg) > 0: - (dud, this_book) = bible_books[bk] - if not this_book in clip_list[int(idx)+1]: - continue - # psg = '[??? Relationship questionable] ' + psg - clip_list[int(idx)+1] += ('\n
Possible Related Bible passage:
' + psg + '\n') - reply = azure_translate_text(reply, language) - translation_count += update_translation_count(len(reply), language) - tokens_in += completion.usage.prompt_tokens - tokens_out += completion.usage.completion_tokens - tokens += completion.usage.total_tokens - response += "\n\n***YOU***: " + prompt_bare + "\n\n***GPT***: " + reply.replace('```','\n\n```\n\n') - # if SLICE_TRANS: - if translation_count > 0: - with open(dataDir + user_window + '_translation.txt','a') as f: - f.write(f'Translation:{translation_count}\n') - if len(clip_list) > 0: - response += md(' '.join(map(str, clip_list))) - if len(bible_list) > 0: - response += md(' '.join(map(str, bible_list))) + if not msg == 'ok': + return [past, msg, None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] + if not chatType in special_chat_types: + reply = response_result.output_text + final_text = reply + tokens_in = response_result.usage.input_tokens + tokens_out = response_result.usage.output_tokens + tokens = response_result.usage.total_tokens + if len(query) > 0: + prompt = 'Search topic = ' + prompt + ', query = ' + query + if etext or last_date: + frag = 'Email Summary' + if last_date: + frag += f" (limited to mail received on/after {last_date})" + response += f"\n\n***{frag}***:\n\n***GPT***: " + reply.replace('```','\n\n```\n\n') + else: + response += "\n\n***YOU***: " + prompt + "\n\n***GPT***: " + reply.replace('```','\n\n```\n\n') if isBoss: response += md(f"\n\n{reporting_model}: tokens in/out = {tokens_in}/{tokens_out}\n") if finish_reason != 'ok': response += md(f"\n{finish_reason}\n") - if tokens > 40000: - response += "\n\nTHIS DIALOG IS GETTING TOO LONG. PLEASE RESTART CONVERSATION SOON." - past.append({"role":"assistant", "content": reply}) - accessOk = False - for i in range(3): - try: - dataFile = new_func(user_window) - with open(dataFile, 'a') as f: - m = '4omini' - f.write(f'{user_window}:{tokens_in}/{tokens_out}-{m}\n') - if (prompt_tokens + total_tokens) > 0: - f.write(f'{user_window}:{prompt_tokens}/{total_tokens}-embed\n') - accessOk = True - break - except Exception as e: - sleep(3) - if not accessOk: - response += f"\nDATA LOG FAILED, path = {dataFile}" - return [past, response , None, gptModel,clip_txt] + past.append({"role":"assistant", "content": final_text}) + if not reasoning: + accessOk = False + for i in range(3): + try: + dataFile = new_func(user_window) + with open(dataFile, 'a') as f: + m = '4o' + if 'mini' in reporting_model: + m = '4omini' + f.write(f'{user_window}:{tokens_in}/{tokens_out}-{m}\n') + accessOk = True + break + except Exception as e: + sleep(3) + if not accessOk: + response += f"\nDATA LOG FAILED, path = {dataFile}" + return [past, response , None, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] else: - return [[], "User name and/or password are incorrect", prompt, gptModel,clip_txt] + return [[], "User name and/or password are incorrect", prompt, gptModel, uploaded_image_file, plot, image_out, file_out, uploaded_file_path] def new_func(user): dataFile = dataDir + user + '_log.txt' return dataFile -# def transcribe(user, pwd, fpath): -# user = user.lower().strip() -# pwd = pwd.lower().strip() -# if not (user in unames and pwd in pwdList): -# return 'Bad credentials' -# with audioread.audio_open(fpath) as audio: -# duration = int(audio.duration) -# if duration > 0: -# with open(dataDir + user + '_audio.txt','a') as f: -# f.write(f'audio:{str(duration)}\n') -# with open(fpath,'rb') as audio_file: -# transcript = Client().audio.transcriptions.create( -# model='whisper-1', file = audio_file ,response_format = 'text' ) -# reply = transcript -# return str(reply) - -# def pause_message(): -# return "Audio input is paused. Resume or Stop as desired" +def image_count_path(user): + fpath = dataDir + user + '_image_count.txt' + return fpath + +def transcribe(user, pwd, fpath): + user = user.lower().strip() + pwd = pwd.lower().strip() + if not (user in unames and pwd in pwdList): + return 'Bad credentials' + with audioread.audio_open(fpath) as audio: + duration = int(audio.duration) + if duration > 0: + with open(dataDir + user + '_audio.txt','a') as f: + f.write(f'audio:{str(duration)}\n') + with open(fpath,'rb') as audio_file: + transcript = Client().audio.transcriptions.create( + model='whisper-1', file = audio_file ,response_format = 'text' ) + reply = transcript + return str(reply) + +def pause_message(): + return "Audio input is paused. Resume or Stop as desired" + +# def gen_output_audio(txt): +# if len(txt) < 10: +# txt = "This dialog is too short to mess with!" +# response = Client().audio.speech.create(model="tts-1", voice="fable", input=txt) +# with open(speak_file, 'wb') as fp: +# fp.write(response.content) +# return speak_file + + +# def set_speak_button(txt): +# vis = False +# if txt and len(txt) > 2: +# vis = True +# return gr.Button(visible=vis) def update_user(user_win): user_win = user_win.lower().strip() @@ -961,18 +1386,18 @@ def update_user(user_win): break return [user, user] -# def speech_worker(chunks=[],q=[]): -# for chunk in chunks: -# fpath = q.pop(0) -# response = Client().audio.speech.create(model="tts-1", voice="fable", input=chunk, speed=0.85, response_format='wav') -# with open(fpath, 'wb') as fp: -# fp.write(response.content) +def speech_worker(chunks=[],q=[]): + for chunk in chunks: + fpath = q.pop(0) + response = Client().audio.speech.create(model="tts-1", voice="fable", input=chunk, speed=0.85, response_format='wav') + with open(fpath, 'wb') as fp: + fp.write(response.content) -# def gen_speech_file_names(user, cnt): -# rv = [] -# for i in range(0, cnt): -# rv.append(dataDir + f'{user}_speech{i}.wav') -# return rv +def gen_speech_file_names(user, cnt): + rv = [] + for i in range(0, cnt): + rv.append(dataDir + f'{user}_speech{i}.wav') + return rv def final_clean_up(user, do_b64 = False): user = user.strip().lower() @@ -980,14 +1405,24 @@ def final_clean_up(user, do_b64 = False): flist = glob(dataDir + '*') elif user == 'all': flist = glob(dataDir + '*_speech*.wav') + if do_b64: + flist.extend(glob(dataDir + '*.b64')) else: flist = glob(dataDir + f'{user}_speech*.wav') + if do_b64: + flist.append(dataDir + user + '_image.b64') + flist.append(dataDir + user + '_image.jpg') for fpath in flist: try: os.remove(fpath) except: continue +def delete_image(user): + fpath = dataDir + user + '.png' + if os.path.exists(fpath): + os.remove(fpath) + def list_permanent_files(): flist = os.listdir(dataDir) others = [] @@ -1008,174 +1443,366 @@ def list_permanent_files(): list_logs = [] return (str(log_cnt), str(wav_cnt), str(other_cnt), str(others), list_logs) +def make_image(prompt, user, pwd): + user = user.lower().strip() + msg = 'Error: unable to create image.' + fpath = None + model = IMAGE_MODEL + quality = 'medium' + size = '1536x1024' + if user in unames and pwd == pwdList[unames.index(user)]: + if len(prompt.strip()) == 0: + return [gr.Image(value=None, visible=False), 'You must provide a prompt describing image you desire'] + if prompt.startswith('hd '): + prompt = prompt[3:] + quality = 'high' + elif prompt.startswith('sd '): + prompt = prompt[3:] + quality = 'low' + elif prompt.startswith('super '): + prompt = prompt[6:] + model = IMAGE_MODEL_BEST + quality = 'high' + yield [gr.Image(value=None, visible=False), "Be patient,this may take a minute or two"] + try: + response = Client().images.generate(model=model, prompt=prompt, quality=quality, + size=size, partial_images=3, stream=True) + except Exception as ex: + msg = ex.message + return [gr.Image(visible=False, value=None), msg] + + pnum = -1 + msgs = ["Working on it ...","Making progress ...", + "Getting closer ...", "Almost there ..."] + for event in response: + if event.type == "image_generation.partial_image": + idx = event.partial_image_index + image_base64 = event.b64_json + image_bytes = base64.b64decode(image_base64) + fpath = dataDir + user + '.png' + with open(fpath, "wb") as fp: + fp.write(image_bytes) + pnum += 1 + yield(gr.Image(value=None, visible=False), msgs[pnum]) + + msg = 'Image created!' + else: + msg = 'Incorrect user name or password' + return [gr.Image(visible=False, value=None), msg] + yield [gr.Image(visible=True, value=fpath), msg] def show_help(): txt = ''' - MTOI Search scans a database you select that contains transcripts of MTOI video teachings, or the - ISR Scriptures, finding sections/passages that relate to the question or topic you enter. - It formulates a response based on that text found. It appends to the response as - follows: - - For video teachings, it lists at least five text clips plus YouTube links to - the video at the point when that text is spoken. Prompts may be entered in either - English or the selected translation language. Responses will be given in the - selected translation language. If you check "Find bible verses mentioned in selected teachings", - Each teaching excerpt will (1) Display and highlight books mentioned and - (2) AI will attempt to discern Book/Chapter/Verse citations and will display the related - passage text following the teaching excerpt. - - For ISR_Bible searches, it lists up to ten bible passages. The AI response will be - given in the selected translation language but the ISR Bible verses remain as found. - Prompts/questions should be entered in English 1. Gemeral: 1.1 Login with user name and password (not case-sensitive) - 1.2 Select a database (topic) using "Choose Topic". You can target all the teaching - video databases by selecting "All Teaching Topics". Note: This selection does not - include ISR_Bible scripture in the search. Bible and teachings searches are two - distinct procedures and cannot be combined. - 1.3 Select a Translation language (initially defaults to "English") - 1.4 Type prompts (questions, topics) into "Prompt or Question" window. - 1.5 For teaching videos, you can limit results based on the dates when the results were uploaded to YouTube with the - Start Date and End Date entries. - 1.6 For ISR_Bible searches, you can filter searches to any selection of books by checking - Activate Filter and selecting book(s) you want to limit search to. - 2. Search: - 2.1 Enter prompt/question and tap the "Submit Prompt/Question" button. The responses appear in the Dialog window. - 2.2 Enter follow-up questions in the Prompt window. Then tap "Submit Prompt/Question". - 2.3 If topic changes, or when done chatting, tap the "Restart Conversation" button. + 1.2 Type prompts (questions, instructions) into "Prompt or Question" window (OR) you can speak prompts by + tapping the audio "Record" button, saying your prompt, then tapping the "Stop" button. + Your prompt will appear in the Prompt window, and you can edit it there if needed. + 1.3 Text in the "Dialog" window can be spoken by tapping the "Speak Dialog" button. + 2. Select Mode: + 2.1 Chat mode interacts with the GPT model with info limited to when last trained. + 2.2 News mode searches the internet for news posted within the period selected in "News Window" + 2.3 Search mode searches the internet based on prompt as topic. Optionally if you prompt with + \ **q:** \, it searches topic and answers question based on search results. + 3. Chat: + 3.1 Enter prompt and tap the "Submit Prompt/Question" button. The responses appear in the Dialog window. + 3.2 Enter follow-up questions in the Prompt window either by typing or speaking. Tap the voice + entry "Reset Voice Entry" button to enable additional voice entry. Then tap "Submit Prompt/Question". + 3.3 If topic changes or when done chatting, tap the "Restart Conversation" button. + 4. Solve math equations or logic problems providing step-by-step analysis, using Chat mode: + 4.1 Math: Make "solve" the first word in your prompt, followed by the equation, e.g., x^2 - x + 1 = 0 + 4.2 Logic: Make "puzzle" the first word in your prompt, followed by a detailed description of a logic + problem with the answer(s) you desire. + 5. Make Image: + 5.1 Enter description of desired image in prompt window via either typing or voice entry + 5.2 Tap the "Make Image" button. This can take a few seconds. + 5.3 There is a download button on the image display if your system supports file downloads. + 5.4 When done viewing image, tap the "Restart Conversation" button + 6. Analyze an Image you provide: + 6.1 Enter what you want to know about the image in the prompt window. You can include instructions + to write a poem about something in the image, for example. Or just say "what's in this image?" + 6.2 Tap the "Upload Image to Analyze" button. + 6.3 An empty image box will appear lower left. Drag or upload image into it. It offers web cam or camera + input also. + 6.4 The image should appear. This can take some time with a slow internet connection and large image. + 6.5 Tap the "Submit Prompt/Question" button to start the analysis. This initiates a chat dialog and + you can ask follow-up questions. However, the image is not re-analyzed for follow-up dialog. Hints: - 1. Better chat results are obtained by including more detail in prompts. Say what you want to know. - You can ask for complex results like: "List the important points of these teachings". - 2. Always tap "Restart Conversation" before changing chat topics. - ''' + 1. Better chat and image results are obtained by including detailed descriptions and instructions + in the prompt. + 2. Always tap "Restart Conversation" before requesting an image or changing topics. + 3. Audio input and output functions depend on the hardware capability of your device. + 4. "Speak Dialog" will voice whatever is currently in the Dialog window. You can repeat it and you + can edit what's to be spoken. Except: In a chat conversation, spoken dialog will only include + the latest prompt/response ("YOU:/GPT:") sequence.''' return str(txt).replace('```', ' ').replace(' ', '  ').replace(' ', '  ').replace(' ', '  ').replace('\n','
') -def upload_db_file(visibility): - viz = not visibility - return [viz, gr.File(visible=viz, type="filepath", interactive=True, label='Upload Database')] +def upload_image(prompt, user, password, mode): + if not (user in unames and password == pwdList[unames.index(user)]): + return [gr.Image(visible=False, interactive=True), "Incorrect user name and/or password"] + if len(prompt) < 3 and mode != 'Advanced': + return [gr.Image(visible=False, interactive=True), "You must provide prompt/instructions (what to do with the image)"] + return [gr.Image(visible=True, interactive=True), ''] -def add_video(video_name, video_list): - db_names = [key for key, value in button_names.items() if value == video_name] - if len(db_names) > 0: - db_name = db_names[0] - else: - db_name = video_name - if db_name in video_list: - video_list.remove(db_name) - return [video_list, gr.Button(video_name, variant="secondary")] - else: - video_list.append(db_name) - return [video_list, gr.Button(video_name, variant="primary")] +def load_image(image, user, mode): + status = 'OK, image is ready! Tap "Submit Prompt/Question" to start analyzing' + try: + with open(image, 'rb') as image_file: + base64_image = base64.b64encode(image_file.read()).decode('utf-8') + if mode == 'Advanced': + if "," in base64_image: + base64_image = base64_image.split(",")[1] + image_data = base64.b64decode(base64_image) + fpath = dataDir + user + "_image.jpg" + with open(fpath, "wb") as fp: + fp.write(image_data) + else: + fpath = dataDir + user + '_image.b64' + with open(fpath, 'wt') as fp: + fp.write(base64_image) + except: + status = 'Unable to upload image' + return [fpath, status] -with gr.Blocks() as demo: # theme=gr.themes.Soft() +def analyze_image(user, model, prompt): + status = 'ok' + try: + with open(dataDir + user + '_image.b64', 'rt') as fp: + base64_image = fp.read() + except: + status = "base64 image file not found" + return [None, status] + + try: + response = Client().responses.create( + model=model, + input=[ + { + "role": "user", + "content": [ + {"type": "input_text", "text": prompt}, + { + "type": "input_image", + "image_url": f"data:image/jpeg;base64,{base64_image}", + }, + ], + } + ], + max_output_tokens=5000, + ) + if response.incomplete_details: + status = response.incomplete_details.reason + except Exception as e: + response = None + status = str(e) + return [response, status] + +def mode_change(mode): + if mode != "News": + return gr.Dropdown(visible=False) + else: + return gr.Dropdown(visible=True, value='pd') + +def upload_file(user, password): + if not (user in unames and password == pwdList[unames.index(user)]): + return [gr.File(visible=False, label='Upload File'), 'Incorrect user and/or password'] + return [gr.File(visible=True, label='UploadFile'), ''] + +def load_file(file, user): + fname = os.path.basename(file.name) + out_path = dataDir + user + '-' + fname + with open(file.name, 'rb') as fp: + data = fp.read() + with open(out_path, 'wb') as fp2: + fp2.write(data) + return [out_path, f'File {fname} uploaded\n'] + +# def auto_test(): +# return dataDir + 'test.wav' + +with gr.Blocks() as demo: history = gr.State([]) password = gr.State("") user = gr.State("unknown") - model = gr.State("gpt-6.1-sol") # 4o-mini") - clip_text = gr.State("") - file_browser_visibility = gr.State(False) - en_hebrew = gr.State({}) - bible_books = gr.State({}) - reverse_bible_books = gr.State({}) - book_filter_active = gr.State(False) - video_list = gr.State([]) - - def expand_accordian(db_chooser): - if db_chooser != "Selected Teachings": - gr.Warning("Can't select teachings unless 'Selected Teachings' source is chosen", - duration=2) - - gr.Markdown('# MTOI Search') + model = gr.State(DEFAULT_MODEL) + q = gr.State([]) + qsave = gr.State([]) + uploaded_image_file = gr.State('') + uploaded_file_path = gr.State('') + + def clean_up(user): + flist = glob(dataDir + f'{user}_speech*.wav') + for fpath in flist: + try: + os.remove(fpath) + except: + continue + + def initial_audio_output(txt, user): + global digits + global abbrevs + if not user in unames: + return [gr.Audio(sources=None), []] + clean_up(user) + q = [] + if len(txt.strip()) < 5: + return ['None', q] + try: + loc = txt.rindex('***YOU***:') + txt = txt[loc:] + except: + pass + for s,x in abbrevs.items(): + txt = txt.replace(s, x) + words_in = txt.replace('**', '').replace(' ','').split('
') + words_out = [] + for s in words_in: + s = s.lstrip('- *@#$%^&_=+-') + if len(s) > 0: + loc = s.find(' ') + if loc > 1: + val = s[0:loc] + isnum = val.replace('.','0').isdecimal() + if isnum: + if val.endswith('.'): + val = val[:-1].replace('.',' point ') + '., ' + else: + val = val.replace('.', ' point ') + ', ' + s = 'num'+ val + s[loc:] + words_out.append(s) + chunklist = [] + for chunk in words_out: + if chunk.strip() == '': + continue + isnumbered = chunk.startswith('num') + number = '' + loc = 0 + if isnumbered: + chunk = chunk[3:] + loc = chunk.index(',') + number = chunk[0:loc] + chunk = chunk[loc:] + locs = [] + for i in range(1,len(chunk)-1): + (a, b, c) = chunk[i-1:i+2] + if a.isdecimal() and b == '.' and c.isdecimal(): + locs.append(i) + for i in locs: + chunk = chunk[:i] + ' point ' + chunk[i+1:] + if len(chunk) > 50: + finechunks = chunk.split('.') + for fchunk in finechunks: + if isnumbered: + fchunk = number + fchunk + isnumbered = False + if len(fchunk) > 0: + if fchunk != '"': + chunklist.append(fchunk) + else: + line = number + chunk + if line != '"': + chunklist.append(line) + total_speech = 0 + for chunk in chunklist: + total_speech += len(chunk) + with open(dataDir + user + '_speech.txt','a') as f: + f.write(f'speech:{str(total_speech)}\n') + chunk = chunklist[0] + if chunk.strip() == '': + return gr.Audio(sources=None) + fname_list = gen_speech_file_names(user, len(chunklist)) + q = fname_list.copy() + qsave = fname_list.copy() + fname = q.pop(0) + if len(chunklist) > 0: + threading.Thread(target=speech_worker, daemon=True, args=(chunklist[1:],fname_list[1:])).start() + response = Client().audio.speech.create(model="tts-1", voice="fable", speed=0.85, input=chunk, response_format='wav') + with open(fname, 'wb') as fp: + fp.write(response.content) + return [fname, q] + + def gen_output_audio(q, user): + try: + fname = q.pop(0) + except: + final_clean_up(user) + return [None, gr.Audio(sources=None)] + if not os.path.exists(fname): + sleep(3) + if not os.path.exists(fname): + response = Client().audio.speech.create(model="tts-1", voice="fable", + input='Sorry, text-to-speech is responding too slow right now', speed=0.85, response_format='wav') + with open(fname, 'wb') as fp: + fp.write(response.content) + q = [] + return [fname, q] + + gr.Markdown('# GPT Chat') gr.Markdown('Enter user name & password. Tap "Help & Hints" button for more instructions.') - # timer = gr.Timer(value=2.0, active=True) with gr.Row(): user_window = gr.Textbox(label = "User Name") user_window.blur(fn=update_user, inputs=user_window, outputs=[user, user_window]) pwd_window = gr.Textbox(label = "Password") help_button = gr.Button(value='Help & Hints') - # with gr.Row(): - # audio_widget = gr.Audio(type='filepath', format='wav',waveform_options=gr.WaveformOptions( - # show_recording_waveform=True), sources=['microphone'], scale = 3, label="Prompt/Question Voice Entry", max_length=120) - # reset_button = gr.ClearButton(value="Reset Voice Entry", scale=1) #new_func1() with gr.Row(): - clear_button = gr.Button(value="Restart Conversation", scale=3) - db_chooser = gr.Dropdown(type="value", label='Choose Source', show_label=True, scale=4, - choices=['All Teachings', 'Selected Teachings', 'ISR Bible'], - interactive=True) - lang_chooser = gr.Dropdown(label='Translation',show_label=True, scale=3, - choices=[('English','en'),('Hebrew','he'),('Spanish','es'),('German','de'),('French','fr'), - ('Japanese','ja'),('Romanian', 'ro'),('Afrikaans', 'af')], - interactive = True) - button_upload_db = gr.Button(value='Upload Database', visible=False, scale=2) - # speak_output = gr.Button(value="Speak Dialog", visible=True, scale=2) - submit_button = gr.Button(value="Submit Prompt/Question", scale=4) + audio_widget = gr.Audio(type='filepath', format='wav',waveform_options=gr.WaveformOptions( + show_recording_waveform=True), sources=['microphone'], scale = 3, label="Prompt/Question Voice Entry") # , max_length=120) + reset_button = gr.ClearButton(value="Reset Voice Entry", scale=1) #new_func1() with gr.Row(): - with gr.Column(scale=3): - find_verses = gr.Checkbox( - label='Find bible verses mentioned in selected teachings', - value=False) - prompt_window = gr.Textbox(label = "Prompt or Question", scale=3) - with gr.Column(scale=2): - filter_heading = gr.Markdown('### **Optional Date Filter. Most common formats are OK
such as   12/2004,     jan 2015,     4 Dec 2012**') - with gr.Row(): - start_date = gr.Textbox(label='Start Date (YYYY-mm-dd)', scale =1,value='1990-01-01',max_lines=1) - end_date = gr.Textbox(label='End Date (YYYY-mm-dd)', scale =1,value=etz_now(),max_lines=1) - checkbox_filter = gr.Checkbox(label='Activate Book Filter', scale=2, - show_label=True, visible=False) - book_chooser = gr.Dropdown(choices=[],type='value', scale=3, - multiselect=True, interactive=False, - label='Book Filter, Select one or more', visible=False) + clear_button = gr.Button(value="Restart Conversation") + button_do_image = gr.Button(value='Make Image') + button_upload_file = gr.Button(value='Upload Input File') + button_get_image = gr.Button(value='Upload Image to Analyze') + speak_output = gr.Button(value="Speak Dialog", visible=True) + submit_button = gr.Button(value="Submit Prompt/Question") with gr.Row(): - accordian = gr.Accordion("Select Individual Teachings. Pull up to free space.", - open=True,visible=True) - accordian.expand(expand_accordian, - inputs=[db_chooser], - outputs=[]) - accordian.collapse(expand_accordian, - inputs=[db_chooser], - outputs=[]) - - with accordian: - video_group = gr.Group(visible=False) - with video_group: - for db_names in db_array: - with gr.Row(equal_height=True): - for db_name in db_names: - btn = gr.Button(button_names.get(db_name, db_name), - variant="secondary", - interactive=(len(db_name) > 0)) - btn.click(fn=add_video, - inputs=[btn, video_list], - outputs=[video_list, btn]) + prompt_window = gr.Textbox(label = "Prompt or Question", scale=7) + mode = gr.Dropdown(choices=[ 'Chat', 'News', 'Search'], label='Mode', scale=1, interactive=True) + news_period = gr.Dropdown(choices=news_interval_choices, + interactive=True,label='News Window',scale=1, visible=False) gr.Markdown('### **Dialog:**') + #output_window = gr.Text(container=True, label='Dialog') output_window = gr.Markdown(container=True) + file_download = gr.DownloadButton(label='Download File', visible=False, value=None) with gr.Row(): - db_file = gr.File(visible=False, type="filepath", interactive=True, label='Upload Database') - pwd_window.blur(updatePassword, inputs = [user_window, pwd_window], outputs = [password, pwd_window, button_upload_db]) + with gr.Column(): + image_window2 = gr.Image(visible=False, interactive=True, label='Image to Analyze', type='filepath') + with gr.Column(): + image_window = gr.Image(visible=False, label='Generated Image') + with gr.Row(): + file_uploader = gr.File(visible=False, label='Upload File', type='filepath') + with gr.Row(): + plot = gr.LinePlot(test_plot_df(), x="month", y="value", visible=False, label="Portfolio Value History") submit_button.click(chat, - inputs=[prompt_window, user_window, password, history, output_window, - model, clip_text, db_chooser,start_date,end_date, lang_chooser, - en_hebrew, book_chooser, book_filter_active, find_verses, - bible_books, reverse_bible_books, video_list], - outputs=[history, output_window, prompt_window, model, clip_text]) - clear_button.click(fn=new_conversation, inputs=[user_window], - outputs=[prompt_window, history, output_window, clip_text, start_date, end_date]) + inputs=[prompt_window, user_window, password, history, output_window, model, + uploaded_image_file, plot, news_period, mode, uploaded_file_path], + outputs=[history, output_window, prompt_window, model, uploaded_image_file, plot, + image_window, file_download, uploaded_file_path]) + clear_button.click(fn=new_conversation, inputs=user_window, + outputs=[prompt_window, history, output_window, image_window, image_window2, + uploaded_image_file, plot, news_period, mode, file_download, uploaded_file_path, + file_uploader]) + audio_widget.stop_recording(fn=transcribe, inputs=[user_window, password, audio_widget], + outputs=[prompt_window]) + audio_widget.pause_recording(fn=pause_message, outputs=[prompt_window]) + reset_button.add(audio_widget) + audio_out = gr.Audio(type='filepath', autoplay=True, visible='hidden') # visible=False) + audio_out.stop(fn=gen_output_audio, inputs=[q, user_window], outputs = [audio_out, q]) + speak_output.click(fn=initial_audio_output, inputs=[output_window, user_window], outputs=[audio_out, q]) + # speak_output.click(fn=auto_test,outputs=audio_out) + # output_window.change(fn=set_speak_button, inputs=output_window,outputs=speak_output) + button_do_image.click(fn=make_image, + inputs=[prompt_window,user_window, password], + outputs=[image_window, output_window]) + image_window.change(fn=delete_image, inputs=[user]) help_button.click(fn=show_help, outputs=output_window) - button_upload_db.click(fn=upload_db_file,inputs = [file_browser_visibility], - outputs = [file_browser_visibility, db_file]) - db_file.upload(fn=write_db_file, inputs=[db_file], outputs=[output_window]) - db_chooser.input(fn=on_db_change,inputs= [db_chooser, bible_books, - book_filter_active], - outputs= [filter_heading, start_date, end_date, book_chooser, - checkbox_filter, find_verses, book_filter_active, video_group]) - # timer.tick(fn=init_db_and_bible_books, inputs=[en_hebrew, bible_books, reverse_bible_books], - # outputs=[timer, db_chooser, end_date, en_hebrew, bible_books, reverse_bible_books]) - demo.load(fn=init_db_and_bible_books, inputs=[en_hebrew, bible_books, reverse_bible_books], - outputs=[end_date, en_hebrew, bible_books, reverse_bible_books]) - checkbox_filter.input(fn=populate_book_chooser, - inputs=[checkbox_filter, bible_books], - outputs=[book_chooser, book_filter_active]) - -demo.queue() + button_get_image.click(fn=upload_image,inputs = [prompt_window, user, password, mode], + outputs = [image_window2, output_window]) + image_window2.upload(fn=load_image, inputs=[image_window2, user, mode], outputs=[uploaded_image_file, output_window]) + mode.change(fn=mode_change, inputs=mode,outputs=news_period) + pwd_window.blur(updatePassword, inputs = pwd_window, outputs = [password, pwd_window, mode]) + button_upload_file.click(fn=upload_file, inputs=[user, password], + outputs=[file_uploader, output_window]) + file_uploader.upload(fn=load_file, inputs=[file_uploader, user], outputs=[uploaded_file_path, output_window]) + # demo.unload(final_clean_up(user)) demo.launch(share=True, allowed_paths=[dataDir], ssr_mode=False, theme=gr.themes.Soft()) -