Skip to content

Instantly share code, notes, and snippets.

@opsJson
Created April 19, 2024 19:02
Show Gist options
  • Save opsJson/e7232c1d584ec17b22b4e27a1fdb7556 to your computer and use it in GitHub Desktop.
Save opsJson/e7232c1d584ec17b22b4e27a1fdb7556 to your computer and use it in GitHub Desktop.
Colador de Prova em Python
import openai
from doctr.models import ocr_predictor
from doctr.io import DocumentFile
from telegram.ext import ApplicationBuilder, MessageHandler, filters
TELEGRAM_TOKEN = "telegram_token_here"
OPENAI_TOKEN = "openai_token_here"
def image_to_text(image_path):
image = DocumentFile.from_images(image_path)
result = model(image)
text = ""
for page in result.pages:
for block in page.blocks:
for line in block.lines:
for word in line.words:
text = text + f"{word.value} "
text = text + "\n"
return text
def text_to_response(text):
try:
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "Responda a seguinte questão:"},
{"role": "user", "content": text}
]
)
return response["choices"][0]["message"]["content"];
except Exception as e:
return str(e)
async def handle_photo(update, context):
photo = update.message.photo[-1]
await update.message.reply_text("Recebendo imagem...")
file = await context.bot.get_file(photo.file_id)
await file.download_to_drive("image.jpg")
await update.message.reply_text("Lendo imagem...")
text = image_to_text("image.jpg")
if len(text) == 0:
await update.message.reply_text("Não foi possível ler a imagem!")
return
await update.message.reply_text(text)
await update.message.reply_text("Pensando...")
response = text_to_response(text)
await update.message.reply_text(response)
async def handle_text(update, context):
text = update.message.text
await update.message.reply_text("Pensando...")
response = text_to_response(text)
await update.message.reply_text(response)
model = ocr_predictor(det_arch="db_resnet50", reco_arch="crnn_vgg16_bn", pretrained=True)
openai.api_key = OPENAI_TOKEN
app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()
app.add_handler(MessageHandler(filters.PHOTO, handle_photo))
app.add_handler(MessageHandler(filters.TEXT, handle_text))
print("Colador de Prova ONLINE!")
app.run_polling()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment