NotesTranscriber / app.py.old2
kgauvin603's picture
Rename app.py to app.py.old2
55cbe72 verified
raw
history blame
3.06 kB
import base64
import os
from datetime import datetime
from openai import OpenAI
import gradio as gr
import oci
# === OpenAI API Setup ===
openai_api_key = os.environ.get("OPENAI_API_KEY")
if not openai_api_key:
raise ValueError("OPENAI_API_KEY environment variable is not set.")
client = OpenAI(api_key=openai_api_key)
# === OCI Object Storage Setup ===
oci_config = {
"user": os.environ.get("OCI_USER"),
"tenancy": os.environ.get("OCI_TENANCY"),
"fingerprint": os.environ.get("OCI_FINGERPRINT"),
"region": os.environ.get("OCI_REGION"),
"key_content": os.environ.get("OCI_PRIVATE_KEY")
}
# Optional: access OCI Object Storage (if needed)
try:
object_storage = oci.object_storage.ObjectStorageClient(oci_config)
except Exception as e:
print("Failed to initialize OCI Object Storage client:", e)
# === Prompts ===
system_prompt = (
"You are a detail-oriented assistant that specializes in transcribing and polishing "
"handwritten notes from images. Your goal is to turn rough, casual, or handwritten "
"content into clean, structured, and professional-looking text that sounds like it "
"was written by a human—not an AI. You do not include icons, emojis, or suggest next "
"steps unless explicitly instructed."
)
user_prompt_template = (
"You will receive an image of handwritten notes. Transcribe the content accurately, "
"correcting any spelling or grammar issues. Then, organize it clearly with headings, "
"bullet points, and proper formatting. Maintain the original intent and voice of the "
"author, but enhance readability and flow. Do not add embellishments or AI-style phrasing."
)
# === Encode uploaded bytes ===
def encode_image_to_base64(file_bytes):
return base64.b64encode(file_bytes).decode("utf-8")
# === Transcription logic ===
def transcribe_image(file_bytes):
if not file_bytes:
return "No image uploaded."
encoded = encode_image_to_base64(file_bytes)
image_url = f"data:image/jpeg;base64,{encoded}"
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": [
{"type": "text", "text": user_prompt_template},
{"type": "image_url", "image_url": {"url": image_url}}
]}
],
max_tokens=1500
)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return f"🗓️ Transcribed on: {timestamp}\n\n{response.choices[0].message.content}"
# === Gradio Interface ===
with gr.Blocks() as app:
gr.Markdown("## Handwritten Note Transcriber\nUpload a handwritten note image for professional transcription.")
input_file = gr.File(label="Upload image", type="binary", file_types=[".jpg", ".jpeg", ".png"])
output_text = gr.Textbox(label="Transcription Output", lines=30)
input_file.change(fn=transcribe_image, inputs=input_file, outputs=output_text)
# === Launch App ===
if __name__ == "__main__":
app.launch(share=True)