kgauvin603 commited on
Commit
c11c262
·
verified ·
1 Parent(s): 394b6f0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +170 -0
app.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import os
3
+ from datetime import datetime
4
+ from openai import OpenAI
5
+ import gradio as gr
6
+ import oci
7
+ import io
8
+ import re
9
+ from collections import Counter
10
+ import matplotlib.pyplot as plt
11
+ from wordcloud import WordCloud
12
+
13
+ # === OpenAI API Setup ===
14
+ openai_api_key = os.environ.get("OPENAI_API_KEY")
15
+ if not openai_api_key:
16
+ raise ValueError("OPENAI_API_KEY environment variable is not set.")
17
+
18
+ client = OpenAI(api_key=openai_api_key)
19
+
20
+ # === OCI Object Storage Setup ===
21
+ oci_config = {
22
+ "user": os.environ.get("OCI_USER"),
23
+ "tenancy": os.environ.get("OCI_TENANCY"),
24
+ "fingerprint": os.environ.get("OCI_FINGERPRINT"),
25
+ "region": os.environ.get("OCI_REGION"),
26
+ "key_content": os.environ.get("OCI_PRIVATE_KEY")
27
+ }
28
+
29
+ namespace = os.environ.get("OCI_NAMESPACE")
30
+ bucket_name = os.environ.get("OCI_BUCKET_NAME")
31
+
32
+ try:
33
+ object_storage = oci.object_storage.ObjectStorageClient(oci_config)
34
+ except Exception as e:
35
+ print("Failed to initialize OCI Object Storage client:", e)
36
+
37
+ # === Prompts ===
38
+ system_prompt = (
39
+ "You are a detail-oriented assistant that specializes in transcribing and polishing "
40
+ "handwritten notes from images. Your goal is to turn rough, casual, or handwritten "
41
+ "content into clean, structured, and professional-looking text that sounds like it "
42
+ "was written by a human—not an AI. You do not include icons, emojis, or suggest next "
43
+ "steps unless explicitly instructed."
44
+ )
45
+
46
+ user_prompt_template = (
47
+ "You will receive an image of handwritten notes. Transcribe the content accurately, "
48
+ "correcting any spelling or grammar issues. Then, organize it clearly with headings, "
49
+ "bullet points, and proper formatting. Maintain the original intent and voice of the "
50
+ "author, but enhance readability and flow. Do not add embellishments or AI-style phrasing."
51
+ )
52
+
53
+ # === Encode uploaded bytes ===
54
+ def encode_image_to_base64(file_bytes):
55
+ return base64.b64encode(file_bytes).decode("utf-8")
56
+
57
+ # === Upload transcription result to OCI ===
58
+ def upload_to_object_storage(user_name, text):
59
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
60
+ filename = f"{user_name.replace(' ', '_')}_{timestamp}.txt"
61
+ object_storage.put_object(
62
+ namespace_name=namespace,
63
+ bucket_name=bucket_name,
64
+ object_name=filename,
65
+ put_object_body=text.encode("utf-8")
66
+ )
67
+ return filename
68
+
69
+ # === List files in object storage ===
70
+ def list_object_store():
71
+ try:
72
+ objects = object_storage.list_objects(namespace, bucket_name)
73
+ return [obj.name for obj in objects.data.objects if obj.name.endswith(".txt")]
74
+ except Exception as e:
75
+ return [f"Failed to list objects: {str(e)}"]
76
+
77
+ # === View file contents ===
78
+ def view_transcription(file_name):
79
+ try:
80
+ response = object_storage.get_object(namespace, bucket_name, file_name)
81
+ return response.data.text
82
+ except Exception as e:
83
+ return f"Failed to load file: {str(e)}"
84
+
85
+ # === Analyze content with OpenAI ===
86
+ def summarize_selected_files(file_list):
87
+ combined_text = ""
88
+ for name in file_list:
89
+ combined_text += view_transcription(name) + "\n"
90
+ if not combined_text.strip():
91
+ return "No content found."
92
+ response = client.chat.completions.create(
93
+ model="gpt-4-turbo",
94
+ messages=[
95
+ {"role": "system", "content": "You are a summarization expert."},
96
+ {"role": "user", "content": "Please summarize the following transcriptions in detail:\n" + combined_text}
97
+ ],
98
+ max_tokens=1500
99
+ )
100
+ return response.choices[0].message.content
101
+
102
+ def recommend_from_selected_files(file_list):
103
+ combined_text = ""
104
+ for name in file_list:
105
+ combined_text += view_transcription(name) + "\n"
106
+ if not combined_text.strip():
107
+ return "No content found."
108
+ response = client.chat.completions.create(
109
+ model="gpt-4-turbo",
110
+ messages=[
111
+ {"role": "system", "content": "You are an operations consultant."},
112
+ {"role": "user", "content": "Please recommend next steps based on these transcriptions:\n" + combined_text}
113
+ ],
114
+ max_tokens=1500
115
+ )
116
+ return response.choices[0].message.content
117
+
118
+ # === Transcription logic ===
119
+ def transcribe_image(file_bytes, user_name):
120
+ if not file_bytes:
121
+ return "No image uploaded."
122
+ encoded = encode_image_to_base64(file_bytes)
123
+ image_url = f"data:image/jpeg;base64,{encoded}"
124
+ response = client.chat.completions.create(
125
+ model="gpt-4-turbo",
126
+ messages=[
127
+ {"role": "system", "content": system_prompt},
128
+ {"role": "user", "content": [
129
+ {"type": "text", "text": user_prompt_template},
130
+ {"type": "image_url", "image_url": {"url": image_url}}
131
+ ]}
132
+ ],
133
+ max_tokens=1500
134
+ )
135
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
136
+ result = f"🗓️ Transcribed on: {timestamp}\n\n{response.choices[0].message.content}"
137
+ upload_to_object_storage(user_name, result)
138
+ return result
139
+
140
+ # === Gradio Interface ===
141
+ with gr.Blocks() as app:
142
+ gr.Markdown("## Handwritten Note Transcriber & Analyzer")
143
+
144
+ with gr.Row():
145
+ user_dropdown = gr.Dropdown(
146
+ choices=["Jim Goodwin", "Zahabiya Ali rampurawala", "Keith Gauvin"],
147
+ label="Who is uploading this?"
148
+ )
149
+
150
+ input_file = gr.File(label="Upload image", type="binary", file_types=[".jpg", ".jpeg", ".png"])
151
+ output_text = gr.Textbox(label="Transcription Output", lines=30)
152
+ input_file.change(fn=transcribe_image, inputs=[input_file, user_dropdown], outputs=output_text)
153
+
154
+ gr.Button("List Object Store").click(fn=lambda: "\n".join(list_object_store()), outputs=gr.Textbox(label="Object Store Contents"))
155
+
156
+ gr.Markdown("### View Transcription")
157
+ file_selector = gr.Dropdown(choices=list_object_store(), label="Select transcription file")
158
+ view_output = gr.Textbox(label="File Content")
159
+ file_selector.change(fn=view_transcription, inputs=file_selector, outputs=view_output)
160
+
161
+ gr.Markdown("### Summarize or Recommend")
162
+ file_multiselect = gr.Dropdown(choices=list_object_store(), label="Select files to analyze", multiselect=True)
163
+ summary_output = gr.Textbox(label="Summary")
164
+ rec_output = gr.Textbox(label="Recommendations")
165
+ gr.Button("Summarize Files").click(fn=summarize_selected_files, inputs=file_multiselect, outputs=summary_output)
166
+ gr.Button("Recommend from Files").click(fn=recommend_from_selected_files, inputs=file_multiselect, outputs=rec_output)
167
+
168
+ # === Launch App ===
169
+ if __name__ == "__main__":
170
+ app.launch(share=True)