Coverage for lib/lib_prompt.py: 34%
112 statements
« prev ^ index » next coverage.py v7.9.1, created at 2026-01-26 23:58 +0100
« prev ^ index » next coverage.py v7.9.1, created at 2026-01-26 23:58 +0100
1__author__ = 'moilerat'
5def extract_preprompt_from_object_hc(object, default_preprompt = ""):
6 if object.lower() == "cr":
7 return "Please make a report with a few main themes, todos and follow-up of the following by keeping the same language :"
8 elif object.lower() in ["parse_graph", "edit_graph", "create_graph"]:
9 return "Renvoyer un graph au format dot de graphviz."
10 else :
11 print("No preprompt from this object : " + str(object) + " keeping default preprompt .")
12 return default_preprompt
16# TODO VR 27-4-23 Other way :
17prepreprompt = "Please extract by keeping the language the meta instruction to be done on this text, what is the expectation with detailed instruction."
18# TODO VR 27-4-23 Option : accept re-indent (temperature ? not exactly)
20def get_tempdir(privacy):
21 import tempfile
22 if privacy :
23 tempdir = tempfile.mkdtemp()
24 print("Creating tempdir : " + str(tempdir))
25 else :
26 tempdir = "temp"
27 return tempdir
29import sys
33# TODO VR 12-11-23
34#
35# Pour : 0609094354
36# De : 0609094354
37# Le : 2023-11-10 11:19:55
38# Duree : 1 minute 15 secondes
39# Will parse the object : [FREEMOBILE] 0609094354: Nouveau message de: 0609094354
40def parse_phone_from_content_get_mail(lpgss, content, object):
41 print(" Parsing phone : " + str(content))
42 vocal_message = False
43 from_phone = ""
44 receiver_phone = ""
45 if object != None and object != "":
46 # object
47 import re
48 phone_pattern = re.compile(r'\b\d{10}\b')
49 free_pattern = re.compile(r'\[FREEMOBILE\] (\d{10}): Nouveau message de: (\d{10})')
50 phone_numbers = free_pattern.fullmatch(object)
51 if phone_numbers:
52 receiver_phone = phone_numbers.group(1)
53 from_phone = phone_numbers.group(2)
54 print(" Parsed !")
56 vocal_message = True
57 else :
58 vocal_message = False
59 if lpgss:
60 # phone = "0609094354"
61 user = lpgss.get_user_from_phone(receiver_phone)
62 validated_receiver_mail = user["mail"] if user and "mail" in user else "victor@reutenauer.eu"
63 else:
64 print(" Not connected, take default stuff !")
65 validated_receiver_mail = "victor@reutenauer.eu"
66 return vocal_message, from_phone, validated_receiver_mail, receiver_phone
68def prompt_from_mail(server, username, password, port, openai_token,
69 language=None,
70 prefix_prompt_input = "Please make a summary of the following : \n",
71 verbose = False, privacy = False,
72 lib_connect = None,
73 debug = False):
74 tempdir = get_tempdir(privacy)
76 # VR TODO : rajouter une condition, ceci sert à gérer la connexion au système centrale (mais sera rendu moins solide dans différents cas !)
77 try :
78 print(str(sys.path))
79 from auth.lib_conf_system import LibConfSystem as LCS
80 lcs = LCS()
82 from lib.stockage.lib_pg_safia_sys import LibPGSafiaSys
83 (PG_HOST, PG_USER, PG_PASSWORD, PG_DB, PG_PORT) = lcs.get_pg_conf()
84 lpgss_singleton = LibPGSafiaSys(PG_HOST, PG_USER, PG_PASSWORD, PG_DB, PG_PORT)
85 except Exception as e:
86 mail = "victor@reutenauer.eu"
87 lpgss_singleton = None
90 from lib.lib_mail import get_mail
91 try:
92 list_files = get_mail(server, username, password, port, verbose = verbose, tempdir = tempdir, privacy = privacy,
93 debug = debug)
94 except Exception as e:
95 print(str(e))
96 print("No connection to smtp server, no mail to process !")
97 list_files = []
99 if verbose :
100 print(" list_files for APIA : " + str(list_files))
102 from auth.lib_stat_usage import StatUsageAPIA as SUA
103 sua = SUA(lib_at = lib_connect)
105 from auth.lib_cost import CostEstimation as CE
106 ce = CE()
108 result_json = []
110 # TODO VR lib_connect est AT_APIA a ce moment là et non PE pour les OTP !
111 from auth.lib_auth import LibUserDataExternalServices
112 # TODO We should add a link : did someone used your email without your consent !
113 # avec une confirmation que ce n'est pas un changement de choix mais bien une mauvaise utilisation !
114 lib_auth_only_for_mail_sending = LibUserDataExternalServices(type_auth="airtable", lib_at = lib_connect)
116 from lib.lib_safia_system import LibSafiaSystem
117 lss = LibSafiaSystem(lib_user_data_internal=None,
118 lib_auth_user_otp=None, # en fait c'est lib_auth_otp
119 lib_user_data_external=lib_auth_only_for_mail_sending) # Ca c'est lib_auth_from_mail (d'ailleurs plutot dangereux pas vraiment auth!)
121# => ca se percute avec le refactauth la gestion des emails pour le traitement des messages vocaux !
122 # il faut refactorer parse_phone_from_content_get_mail 12-11-23
126 for input in list_files:
127 from_mail = input["from_mail"]
128 file = input["file"]
129 object = input["object"]
130 content = input["content"] if "content" in input else ""
131 vocal_message, from_phone, mail_validated, receiver_phone = parse_phone_from_content_get_mail(lpgss_singleton, content, object)
132 # While decommissionning preprompt
133 prefix_prompt_input = ""
135 # Specifique à prompt_from_mail actuellement
136 preprompt = extract_preprompt_from_object_hc(object, prefix_prompt_input)
137 if vocal_message:
138 preprompt = "Merci de rendre compte rapidement du message vocal suivant qui a été transcrit, il a été laissé par " + from_phone + " on " + receiver_phone + "\n:"
139 from_mail = mail_validated
140 if not privacy:
141 print(" prefix_prompt : " + str(preprompt))
143 from auth.lib_auth import get_datou_exec_context_as_complete_param_json
144 complete_param_json = get_datou_exec_context_as_complete_param_json(from_mail, verbose, privacy, openai_token,
145 lss=lss)
147# list_datou_step = ["extract_text", "speech_to_text", "image_to_text", "extract_meta_instruction", "request_response", "send_mail"], # , "git_ret"
149 if file.endswith(".amr") or file.endswith(".ogg") or file.endswith(".mp3") or file.endswith(".m4a") or file.endswith(".wav"):
150 list_datou_step = ["speech_to_text", "request_gpt", "send_mail"]
151 elif file.lower().endswith(".jpg") or file.lower().endswith(".jpeg") or file.lower().endswith(".png"):
152 list_datou_step = ["image_to_text", "request_gpt", "send_mail"]
153 else :
154 print("Do nothing !")
155 list_datou_step = []
157 if object.lower() == "git":
158 list_datou_step.append("git_action")
159 elif object.lower() == "create_graph":
160 list_datou_step.append("create_graph")
161 elif object.lower() == "edit_graph": # TODO VR 15-6-23 to merge with create_graph
162 list_datou_step.append("edit_graph")
163 else :
164 print("object " + str(object) + " doesn't registered has a specific action (but maybe a preprompt) ")
167 input_datou = {"file" : file, "preprompt" : preprompt}
168 if "cc" in input:
169 input_datou["cc"] = input["cc"]
171 from lib.datou.datou_exec import datou_exec
172 output, audit_json = datou_exec(list_datou_step, input_datou, complete_param_json)
174 result = output["result"] if "result" in output else "NO RESULT IN JSON"
175 request = output["request"]
176 cost = output["cost"]
177 # Pas clair s'il faut garder cette condition, safia est en mode privacy = False
178 if not privacy:
179 json_data = {"request" : request, "result" : result, "cost" : cost}
180 result_json.append(output)
182 # TODO VR : 14-6-23 : prevoir de deprecated vu que personne ne le regarde anyway ! (à moins que !, mais personne ne le sait)
183 if privacy:
184 sua.record_usage(mail = from_mail, cost = cost)
185 else :
186 sua.record_usage(mail = from_mail, cost = cost,
187 input = request, output = result)
189 return result_json
194 # VR ca n'a pas encore fonctionné !
195# if object == "edit_graph":
196# from lib.datou.lib_datou_step_template import datou_safia_step_load_existing_graph
197# output = datou_safia_step_load_existing_graph()
198# print("Never tested !")
199# if "input_graph" in output:
200# input_graph = output["preprompt"]