kgauvin603 commited on
Commit
be120c5
·
verified ·
1 Parent(s): b262d17

Create app.py

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