I'm trying to get the words that are inside my api response, the message variable, that are all inside the document and make only them bold. I've tried in every way, even asking chatgpt for help to make these changes, however, I'm not succeeding.
My code:
import os
import shutil
from docx import Document
import requests
from senhaapi import API_KEY
import json
from docxtpl import DocxTemplate
import docx
from docx.shared import Pt
import re
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
ans = read_multiple_choice(
"Escolha a matéria da prova que será submetida",
[{"label": "Português", "value": "portugues"},
{"label": "Matemática", "value": "matematica"},
{"label": "Geografia", "value": "geografia"},
{"label": "História", "value": "historia"},
{"label": "Física", "value": "fisica"},
{"label": "Química", "value": "quimica"},
{"label": "Literatura", "value": "Literatura"},
{"label": "Inglês", "value": "ingles"},
{"label": "Espanhol", "value": "espanhol"}, ],
)
if ans == "portugues":
print("Processing the file for Português")
file_response = read_file("Enviar")
file_name = file_response.name
# Verificar se o arquivo tem a extensão .docx
if not file_name.endswith(".docx"):
display("A prova enviada deve estar no formato .docx", size='medium')
else:
script_dir = os.getcwd()
destination_dir = os.path.join(script_dir, "foo/bar")
os.makedirs(destination_dir, exist_ok=True)
original_file_path = os.path.join(destination_dir, file_name)
with open(original_file_path, "wb") as destination_file:
shutil.copyfileobj(file_response.file, destination_file)
# Abrir o documento com python-docx
document = Document(original_file_path)
texto_a_adicionar = "Teste"
for paragraph in document.paragraphs:
if not paragraph.text.strip(): # Verificar se o parágrafo está vazio
run = paragraph.add_run(texto_a_adicionar)
font = run.font
font.size = Pt(8)
break # Parar após adicionar o texto
for paragraph in document.paragraphs:
for run in paragraph.runs:
run.font.name = 'Arial'
run.font.size = Pt(14) # Tamanho da fonte em pontos
questoes = {}
questao_atual = None
for paragraph in document.paragraphs:
text = paragraph.text.strip()
if text and text[0].isdigit() and text[1:2] == ")":
if questao_atual is not None:
questoes[questao_numero] = questao_atual.strip()
questao_numero = int(text.split(")", 1)[0])
questao_atual = text.split(")", 1)[1]
else:
if questao_atual is not None:
questao_atual += " " + text
if questao_atual is not None:
questoes[questao_numero] = questao_atual.strip()
keywords = []
for question_number, question_content in questoes.items():
# Split the question content into words
words = re.findall(r'\w+', question_content)
keywords.extend(words) # Add words to the keywords list
api_message = f"Verificar dentro de {', '.join(keywords)} quais são as palavras chaves ou verbos de comando, não mude o tempo verbal das palavras-chaves ou verbos de comando. Só me mostra na resposta apenas o que eu pedi, sem texto antes."
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
link = "https://api.openai.com/v1/chat/completions"
id_modelo = "gpt-3.5-turbo"
body_api = {
"model": id_modelo,
"temperature": 0.3,
"messages": [{"role": "user", "content": api_message}]
}
body_api = json.dumps(body_api)
request = requests.post(link, headers=headers, data=body_api)
response = request.json()
message = response["choices"][0]["message"]["content"]
print(request)
print(request.text)
modified_file_path = os.path.join(destination_dir, "modified_" + file_name)
document.save(modified_file_path)
else:
display("Selecione uma opção válida", size='medium')
I tried this code and it didn't work:
for keyword in unique_keywords:
for paragraph in document.paragraphs:
for run in paragraph.runs:
if keyword in run.text:
new_text = run.text.replace(keyword, f'<w:b>{keyword}</w:b>')
run.text = new_text
api_message = f"Verificar dentro de {', '.join(keywords)} quais são as palavras-chaves ou verbos de comando, não mude o tempo verbal das palavras-chaves ou verbos de comando. Só me mostra na resposta apenas o que eu pedi, sem texto antes."
for paragraph in document.paragraphs:
for word in message.split(): # Divida a mensagem em palavras
if word in paragraph.text:
# Percorra as runs no parágrafo e destaque as palavras em negrito
for run in paragraph.runs:
if word in run.text:
run.bold = True
The display, file_responder, read_multiple_choice are from my work library
Thanks for the help