File size: 7,439 Bytes
f757ba6
 
 
 
 
 
 
 
6eed986
 
 
 
f757ba6
6eed986
f757ba6
6eed986
 
f757ba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eed986
 
 
 
 
 
f757ba6
 
6eed986
 
f757ba6
6eed986
f757ba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eed986
 
f757ba6
 
6eed986
f757ba6
 
 
 
6eed986
f757ba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eed986
f757ba6
6eed986
f757ba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eed986
f757ba6
6eed986
f757ba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eed986
 
 
 
 
f757ba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eed986
f757ba6
 
 
6eed986
f757ba6
6eed986
 
 
 
 
f757ba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eed986
 
 
 
 
f757ba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eed986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
from langchain.docstore.document import Document
from langchain.chains.question_answering import load_qa_chain
import chromadb
from datetime import datetime
import os
from datetime import datetime
import pdfkit
from langchain.chains.question_answering import load_qa_chain
from langchain.prompts import PromptTemplate
from pathlib import Path
import os
from pypdf import PdfReader

from llm_call import SermonGeminiPromptTemplate
bookQuestion = dict()
llm = None
embed_model = None

contemplandoQuestion = {
    'DEVOCIONALMENTE':'¿Cómo estimula Dios su corazón a través de Su Palabra?',
    'EXÉGESIS':'Cuál es el contexto de este pasaje?',
    'CRISTO':'¿Cómo se comprende este texto a la luz de Cristo?',
    'ARCO REDENTOR':'¿Cómo encaja este texto en la metanarrativa de las Escrituras?',
    'EVANGELION': '¿Cómo se declara el evangelio en este texto?',
    'EVANGELION_TWO': '¿Cómo interpretamos este texto a la luz del evangelio?',
     }

proclamandoQuestion = {
     'PÚBLICO':'¿Cuáles son los ídolos en los corazones de las personas que rechazarían el evangelio de Cristo?',
     'HISTORIA':'¿Cómo el guión de su predicación comunica la historia de Dios?',
     'EXPECTATIVAS': '¿Qué espera Dios que hagan como respuesta a esta predicación?',
     'EXPECTATIVAS_TWO': '¿Cuáles son sus expectativas divinas como predicador de este mensaje?',
 }


bookQuestion['Contemplando'] = contemplandoQuestion
bookQuestion['Proclamando'] = proclamandoQuestion

HISTORY_ANSWER = ""

DIRECTORY_PATH_TO_DOWNLOAD = 'data/sermon_lab_ai/download_files'

if not os.path.exists(DIRECTORY_PATH_TO_DOWNLOAD):
  os.makedirs(f"{DIRECTORY_PATH_TO_DOWNLOAD}")

def getCurrentFileName():
  now = datetime.now()
  strNow = now.strftime("%m%d%Y_%H%M%S")
  return f"sermonDay_{strNow}.pdf"

fileAddresToDownload = f"{DIRECTORY_PATH_TO_DOWNLOAD}{os.sep}{getCurrentFileName()}"
FILE_PATH_NAME = fileAddresToDownload

def updatePromptTemplate(promptTemplate, inputVariablesTemplate):
    prompt = PromptTemplate(template = promptTemplate,
                        input_variables = inputVariablesTemplate)
    chain = load_qa_chain(
        llm,
        chain_type = "stuff",
        prompt = prompt
    )

    return chain
def predict(query):
  templates = SermonGeminiPromptTemplate()

  chain = updatePromptTemplate(
      templates.getSermonPromptTemplate('BUILD_PREPARE_QUESTIONS'),
       ['question','SERMON_CONTEXT','context']
    )

  if query != '':
    global retriever
    answer = askQuestion(
        query,
        chain,
        retriever,
        topic = query,
        KEY = 'question'
    )
    answer = (answer.split("<|assistant|>")[-1]).strip()
    HISTORY_ANSWER = answer

    return answer
  else:
    return query

def predictContemplando(queryKey):
  #Call to LLM LangChaing inference
  query = contemplandoQuestion[queryKey]
  return predict(query)


def predictProclamando(queryKey):
  #Call to LLM LangChaing inference
  query = proclamandoQuestion[queryKey]
  return predict(query)

####
#
####
def predictFromInit(sermonTopic):
  global HISTORY_ANSWER
  keyStr = 'SERMON_TOPIC'

  templates = SermonGeminiPromptTemplate()

  if HISTORY_ANSWER == '':
    chain = updatePromptTemplate(
        templates.getSermonPromptTemplates('BUILD_INIT'),
        [keyStr,'CANT_VERSICULOS','context']
        )
  else:
    chain = updatePromptTemplate(
        templates.getSermonPromptTemplates('BUILD_EMPTY'),
        ['BIBLE_VERSICLE','context']
        )
    keyStr = 'BIBLE_VERSICLE'

  global retriever
  answer = askQuestionInit(
      '',
      chain,
      retriever,
      topic = sermonTopic,
      KEY = keyStr
    )

  #Create a new document and build a retriver
  if answer != '':
    doc =  Document(page_content="text", metadata = {"source": "local"})

    vectorstore = Chroma.from_documents(
      documents = [doc],
      embedding = embed_model,
      persist_directory="chroma_db_dir_sermon",  # Local mode with in-memory storage only
      collection_name="sermon_lab_ai"
    )

    retriever = vectorstore.as_retriever(
        search_kwargs = {"k": 3}
    )


  HISTORY_ANSWER = answer

  return answer

####
#
####
def predictQuestionBuild(sermonTopic):
  templates = SermonGeminiPromptTemplate()
  chain = updatePromptTemplate(
      templates.getSermonPromptTemplates('BUILD_QUESTION'),
       ['SERMON_IDEA', 'context']
      )
  global retriever
  answer = askQuestionEx(
      '',
      chain,
      retriever,
      topic = sermonTopic,
      KEY = 'SERMON_IDEA'
    )

  return answer

####
#
####
def predictDevotionBuild(sermonTopic):
  templates = SermonGeminiPromptTemplate()
  chain = updatePromptTemplate(
      templates.getSermonPromptTemplate('BUILD_REFLECTIONS'),
       ['SERMON_IDEA', 'context']
      )
  global retriever
  global HISTORY_ANSWER
  answer = askQuestionEx(
      HISTORY_ANSWER,
      chain,
      retriever,
      topic = sermonTopic,
      KEY = 'SERMON_IDEA'
    )

  return answer


# A utility function for answer generation
def askQuestion(
        question,
        _chain,
        _retriever,
        topic = 'el amor de Dios',
        KEY = 'SERMON_TOPIC'
    ):

   #Obtener los Chunks relevantes a la pregunta en el RAG
   #print(f" Question: {question}")

   context = _retriever.get_relevant_documents(question)

   #print("----  Contexto ----")
   #print(context)
   #print("____________________GLOBAL________")

   global HISTORY_ANSWER

   #print (HISTORY_ANSWER)

   return (
         _chain({
             KEY: topic,
             'SERMON_CONTEXT': HISTORY_ANSWER,
             "input_documents": context,
             "question": question
             },
            return_only_outputs = True)
         )['output_text']


 #A utility function for answer generation
def askQuestionEx(
        question,
        _chain,
        _retriever,
        topic = 'el amor de Dios',
        KEY = 'SERMON_TOPIC'
    ):

   context = _retriever.get_relevant_documents(question)

   global HISTORY_ANSWER

   return (
         _chain({
             KEY: topic,
             "input_documents": context,
             "question": question
             },
            return_only_outputs=True)
         )['output_text']

# A utility function for answer generation
def askQuestionInit(
        question,
        _chain,
        _retriever,
        topic = 'el amor de Dios',
        KEY = 'SERMON_TOPIC'
    ):

   #Obtener los Chunks relevantes a la pregunta en el RAG
   context = _retriever.get_relevant_documents(question)

   settings = {
             KEY: topic,
             "input_documents": context,
             "question": question
             }

   if KEY == 'SERMON_TOPIC':
     settings['CANT_VERSICULOS'] = 5

   return (
         _chain(
            settings,
            return_only_outputs=True)
         )['output_text']


def downloadSermonFile(answer):

  if os.path.exists(FILE_PATH_NAME):
    os.remove(FILE_PATH_NAME)

  pdfkit.from_string(
        answer,
       FILE_PATH_NAME
    )

  return ""


def upload_file_ex(files):
    file_paths = [file.name for file in files]

    for filepath in file_paths:
      name = Path(filepath)
      file_content = 'Empty content'

      if os.path.exists(filepath):
        file_content = ''
        reader = PdfReader(filepath)

        for page in reader.pages:
          file_content += page.extract_text()

        HISTORY_ANSWER = file_content
    return [file_paths, file_content]