kgauvin603 commited on
Commit
f1b6d20
·
verified ·
1 Parent(s): db0bad3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +209 -0
app.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 and Filter ===
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
+ def filter_object_store(query):
79
+ return [name for name in list_object_store() if query.lower() in name.lower()]
80
+
81
+ # === View file contents ===
82
+ def view_transcription(file_name):
83
+ try:
84
+ response = object_storage.get_object(namespace, bucket_name, file_name)
85
+ return response.data.text
86
+ except Exception as e:
87
+ return f"Failed to load file: {str(e)}"
88
+
89
+ # === Analyze content with OpenAI ===
90
+ def summarize_selected_files(file_list):
91
+ combined_text = ""
92
+ for name in file_list:
93
+ combined_text += view_transcription(name) + "\n"
94
+ if not combined_text.strip():
95
+ return "No content found."
96
+ response = client.chat.completions.create(
97
+ model="gpt-4-turbo",
98
+ messages=[
99
+ {"role": "system", "content": "You are a summarization expert."},
100
+ {"role": "user", "content": "Please summarize the following transcriptions in detail:\n" + combined_text}
101
+ ],
102
+ max_tokens=1500
103
+ )
104
+ return response.choices[0].message.content
105
+
106
+ def recommend_from_selected_files(file_list):
107
+ combined_text = ""
108
+ for name in file_list:
109
+ combined_text += view_transcription(name) + "\n"
110
+ if not combined_text.strip():
111
+ return "No content found."
112
+ response = client.chat.completions.create(
113
+ model="gpt-4-turbo",
114
+ messages=[
115
+ {"role": "system", "content": "You are an operations consultant."},
116
+ {"role": "user", "content": "Please recommend next steps based on these transcriptions:\n" + combined_text}
117
+ ],
118
+ max_tokens=1500
119
+ )
120
+ return response.choices[0].message.content
121
+
122
+ # === Generate word cloud from selected files ===
123
+ def generate_word_map_from_files(file_list):
124
+ combined_text = ""
125
+ for name in file_list:
126
+ combined_text += view_transcription(name) + "\n"
127
+ if not combined_text.strip():
128
+ return "No content found."
129
+
130
+ wordcloud = WordCloud(width=800, height=400, background_color='white').generate(combined_text)
131
+ plt.figure(figsize=(10, 5))
132
+ plt.imshow(wordcloud, interpolation='bilinear')
133
+ plt.axis("off")
134
+ buf = io.BytesIO()
135
+ plt.savefig(buf, format="png")
136
+ buf.seek(0)
137
+
138
+ # Upload image to object storage
139
+ filename = f"wordcloud_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
140
+ object_storage.put_object(
141
+ namespace_name=namespace,
142
+ bucket_name=bucket_name,
143
+ object_name=filename,
144
+ put_object_body=buf.read()
145
+ )
146
+
147
+ buf.seek(0)
148
+ return gr.Image.update(value=buf)
149
+
150
+ # === Transcription logic ===
151
+ def transcribe_image(file_bytes, user_name):
152
+ if not file_bytes:
153
+ return "No image uploaded."
154
+ encoded = encode_image_to_base64(file_bytes)
155
+ image_url = f"data:image/jpeg;base64,{encoded}"
156
+ response = client.chat.completions.create(
157
+ model="gpt-4-turbo",
158
+ messages=[
159
+ {"role": "system", "content": system_prompt},
160
+ {"role": "user", "content": [
161
+ {"type": "text", "text": user_prompt_template},
162
+ {"type": "image_url", "image_url": {"url": image_url}}
163
+ ]}
164
+ ],
165
+ max_tokens=1500
166
+ )
167
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
168
+ result = f"🗓️ Transcribed on: {timestamp}\n\n{response.choices[0].message.content}"
169
+ upload_to_object_storage(user_name, result)
170
+ return result
171
+
172
+ # === Gradio Interface ===
173
+ with gr.Blocks() as app:
174
+ gr.Markdown("## Handwritten Note Transcriber & Analyzer")
175
+
176
+ with gr.Row():
177
+ user_dropdown = gr.Dropdown(
178
+ choices=["Jim Goodwin", "Zahabiya Ali rampurawala", "Keith Gauvin"],
179
+ label="Who is uploading this?"
180
+ )
181
+
182
+ input_file = gr.File(label="Upload image", type="binary", file_types=[".jpg", ".jpeg", ".png"])
183
+ output_text = gr.Textbox(label="Transcription Output", lines=30)
184
+ input_file.change(fn=transcribe_image, inputs=[input_file, user_dropdown], outputs=output_text)
185
+
186
+ gr.Markdown("### View Transcription")
187
+ search_box = gr.Textbox(label="Filter by uploader or keyword")
188
+ filtered_dropdown = gr.Dropdown(label="Select transcription file")
189
+ view_output = gr.Textbox(label="File Content")
190
+ search_box.change(fn=filter_object_store, inputs=search_box, outputs=filtered_dropdown)
191
+ filtered_dropdown.change(fn=view_transcription, inputs=filtered_dropdown, outputs=view_output)
192
+
193
+ gr.Markdown("### Summarize or Recommend")
194
+ file_multiselect = gr.Dropdown(choices=list_object_store(), label="Select files to analyze", multiselect=True)
195
+ summary_output = gr.Textbox(label="Summary")
196
+ rec_output = gr.Textbox(label="Recommendations")
197
+ gr.Button("Summarize Files").click(fn=summarize_selected_files, inputs=file_multiselect, outputs=summary_output)
198
+ gr.Button("Recommend from Files").click(fn=recommend_from_selected_files, inputs=file_multiselect, outputs=rec_output)
199
+
200
+ gr.Markdown("### Word Cloud from Files")
201
+ gr.Button("Generate Word Map from Files").click(
202
+ fn=generate_word_map_from_files,
203
+ inputs=file_multiselect,
204
+ outputs=gr.Image()
205
+ )
206
+
207
+ # === Launch App ===
208
+ if __name__ == "__main__":
209
+ app.launch(share=True)