File size: 8,296 Bytes
5a1dd3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import base64
import os
from datetime import datetime, timedelta
from openai import OpenAI
import gradio as gr
import oci
import io
import re
from collections import Counter
import matplotlib.pyplot as plt
from wordcloud import WordCloud

# === 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")
}

namespace = os.environ.get("OCI_NAMESPACE")
bucket_name = os.environ.get("OCI_BUCKET_NAME")

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")

# === Upload transcription result to OCI ===
def upload_to_object_storage(user_name, text):
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"{user_name.replace(' ', '_')}_{timestamp}.txt"
    object_storage.put_object(
        namespace_name=namespace,
        bucket_name=bucket_name,
        object_name=filename,
        put_object_body=text.encode("utf-8")
    )
    return filename

# === List files in object storage ===
def list_object_store():
    try:
        objects = object_storage.list_objects(namespace, bucket_name)
        return "\n".join([obj.name for obj in objects.data.objects if obj.name.endswith(".txt")])
    except Exception as e:
        return f"Failed to list objects: {str(e)}"

# === Download file ===
def download_transcription(file_name):
    try:
        response = object_storage.get_object(namespace, bucket_name, file_name)
        return response.data.text
    except Exception as e:
        return f"Failed to download: {str(e)}"

# === Get files in date range ===
def get_files_by_date_range(start_date, end_date):
    result = []
    objects = object_storage.list_objects(namespace, bucket_name).data.objects
    for obj in objects:
        match = re.search(r'(\d{8}_\d{6})', obj.name)
        if match:
            obj_date = datetime.strptime(match.group(1), "%Y%m%d_%H%M%S")
            if start_date <= obj_date <= end_date:
                result.append(obj.name)
    return result

# === Analyze content with OpenAI ===
def summarize_range(start_date, end_date):
    files = get_files_by_date_range(start_date, end_date)
    combined_text = ""
    for name in files:
        combined_text += download_transcription(name) + "\n"
    if not combined_text.strip():
        return "No content found."
    response = client.chat.completions.create(
        model="gpt-4-turbo",
        messages=[
            {"role": "system", "content": "You are a summarization expert."},
            {"role": "user", "content": "Please summarize the following transcriptions in detail:\n" + combined_text}
        ],
        max_tokens=1500
    )
    return response.choices[0].message.content

def recommend_next_steps(start_date, end_date):
    files = get_files_by_date_range(start_date, end_date)
    combined_text = ""
    for name in files:
        combined_text += download_transcription(name) + "\n"
    if not combined_text.strip():
        return "No content found."
    response = client.chat.completions.create(
        model="gpt-4-turbo",
        messages=[
            {"role": "system", "content": "You are an operations consultant."},
            {"role": "user", "content": "Please recommend next steps based on these transcriptions:\n" + combined_text}
        ],
        max_tokens=1500
    )
    return response.choices[0].message.content

# === Generate word cloud and sentiment mock ===
def generate_word_map(start_date, end_date):
    files = get_files_by_date_range(start_date, end_date)
    combined_text = ""
    for name in files:
        combined_text += download_transcription(name) + "\n"
    if not combined_text.strip():
        return "No content found."
    wordcloud = WordCloud(width=800, height=400, background_color='white').generate(combined_text)
    plt.figure(figsize=(10, 5))
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis("off")
    buf = io.BytesIO()
    plt.savefig(buf, format="png")
    buf.seek(0)
    return gr.Image.update(value=buf)

# === Transcription logic ===
def transcribe_image(file_bytes, user_name):
    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")
    result = f"🗓️ Transcribed on: {timestamp}\n\n{response.choices[0].message.content}"
    upload_to_object_storage(user_name, result)
    return result

# === Gradio Interface ===
with gr.Blocks() as app:
    gr.Markdown("## Handwritten Note Transcriber & Analyzer")

    with gr.Row():
        user_dropdown = gr.Dropdown(
            choices=["Jim Goodwin", "Zahabiya Ali rampurawala", "Keith Gauvin"],
            label="Who is uploading this?"
        )

    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, user_dropdown], outputs=output_text)

    gr.Button("List Object Store").click(fn=list_object_store, outputs=gr.Textbox(label="Object Store Contents"))

    gr.Markdown("### Download or Analyze Transcriptions")
    download_input = gr.Textbox(label="File name to download")
    download_output = gr.Textbox(label="Downloaded Transcription")
    gr.Button("Download File").click(fn=download_transcription, inputs=download_input, outputs=download_output)

    gr.Markdown("### Summarize or Recommend from Date Range")
    start = gr.Textbox(label="Start Date (YYYY-MM-DD)")
    end = gr.Textbox(label="End Date (YYYY-MM-DD)")
    summary_output = gr.Textbox(label="Summary")
    gr.Button("Summarize Range").click(
        fn=lambda s, e: summarize_range(datetime.strptime(s, "%Y-%m-%d"), datetime.strptime(e, "%Y-%m-%d")),
        inputs=[start, end],
        outputs=summary_output
    )

    rec_output = gr.Textbox(label="Recommendations")
    gr.Button("Recommend Next Steps").click(
        fn=lambda s, e: recommend_next_steps(datetime.strptime(s, "%Y-%m-%d"), datetime.strptime(e, "%Y-%m-%d")),
        inputs=[start, end],
        outputs=rec_output
    )

    gr.Markdown("### Word Cloud")
    gr.Button("Generate Word Map").click(
        fn=lambda s, e: generate_word_map(datetime.strptime(s, "%Y-%m-%d"), datetime.strptime(e, "%Y-%m-%d")),
        inputs=[start, end],
        outputs=gr.Image()
    )

# === Launch App ===
if __name__ == "__main__":
    app.launch(share=True)