Rohitface commited on
Commit
39c88cb
·
verified ·
1 Parent(s): 22d2df6

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -0
app.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """app.py
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1fuzwSkyjYRLfvGxQGclxwX0Y9OD2IK6s
8
+ """
9
+
10
+ # app.py
11
+
12
+ # Step 1: Install necessary libraries
13
+ # This is handled by requirements.txt in Hugging Face Spaces,
14
+ # but you would run this line in a fresh environment:
15
+ # !pip install -q gradio transformers torch sentencepiece
16
+
17
+ # Step 2: Import libraries
18
+ import gradio as gr
19
+ import re
20
+ from transformers import pipeline
21
+
22
+ # --- Backend Logic ---
23
+
24
+ # Step 3: Load the Hugging Face Model
25
+ print("Loading Hugging Face model (google/flan-t5-small)... This may take a moment.")
26
+ text_generator = pipeline(
27
+ "text2text-generation",
28
+ model="google/flan-t5-small"
29
+ )
30
+ print("Model loaded successfully!")
31
+
32
+
33
+ def parse_chat_file(file_content):
34
+ """
35
+ A robust parser for both WhatsApp and Telegram text exports.
36
+ """
37
+ lines = file_content.split('\n')
38
+ chat_data = []
39
+ pattern = re.compile(
40
+ r'^(?:\u200e)?\[?(\d{1,2}[/.]\d{1,2}[/.]\d{2,4}),?\s+(\d{1,2}:\d{2}(?::\d{2})?(?:\s*[AP]M)?)\]?\s*-\s*([^:]+):\s*(.*)',
41
+ re.IGNORECASE
42
+ )
43
+ for line in lines:
44
+ match = pattern.match(line)
45
+ if match:
46
+ sender, message = match.group(3), match.group(4)
47
+ if "created this group" not in message and "added" not in message and "changed the subject" not in message:
48
+ chat_data.append(f"{sender}: {message}")
49
+ elif chat_data and line.strip():
50
+ chat_data[-1] += "\n" + line
51
+ return "\n".join(chat_data) if chat_data else "Could not parse chat file."
52
+
53
+
54
+ def process_chat_request(user_question, chat_history, state_data):
55
+ """
56
+ The main function that handles the chat logic using the local Hugging Face model.
57
+ """
58
+ context_size = state_data.get("context_size")
59
+ chat_content = state_data.get("chat_content")
60
+ temperature = state_data.get("temperature")
61
+
62
+ if not all([context_size, chat_content, temperature is not None]):
63
+ raise gr.Error("Chat content or configuration is missing. Please restart by uploading a file.")
64
+ if not user_question:
65
+ raise gr.Error("Please enter a question.")
66
+
67
+ context_to_use = chat_content[-int(context_size):]
68
+
69
+ prompt = f"""
70
+ Based on the following chat history, provide a detailed answer to the user's question.
71
+
72
+ CONTEXT:
73
+ ---
74
+ {context_to_use}
75
+ ---
76
+
77
+ QUESTION: {user_question}
78
+
79
+ ANSWER:
80
+ """
81
+
82
+ try:
83
+ result = text_generator(
84
+ prompt,
85
+ max_length=300,
86
+ num_beams=3,
87
+ temperature=temperature
88
+ )
89
+ bot_response = result[0]['generated_text']
90
+ except Exception as e:
91
+ raise gr.Error(f"An error occurred with the model: {e}")
92
+
93
+ chat_history.append((user_question, bot_response))
94
+ return "", chat_history
95
+
96
+ # --- Gradio UI Definition ---
97
+
98
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", secondary_hue="orange"), title="Local Chat Analyzer") as demo:
99
+ app_state = gr.State({})
100
+
101
+ with gr.Column(visible=True) as welcome_page:
102
+ gr.Markdown(
103
+ """
104
+ <div style='text-align: center; font-family: "Garamond", serif; padding-top: 30px;'>
105
+ <h1 style='font-size: 3.5em;'>Local Chat Analyzer</h1>
106
+ <p style='font-size: 1.5em; color: #555;'>Powered by a Hugging Face Model. No API key needed!</p>
107
+ </div>
108
+ """
109
+ )
110
+ gr.HTML(
111
+ """
112
+ <div style='text-align: center; padding: 20px;'>
113
+ <img src='https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExd2Vjb3M2eGZzN2FkNWZpZzZ0bWl0c2JqZzZlMHVwZ2l4b2t0eXFpcyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/YWjDA4k2n6d5Ew42zC/giphy.gif'
114
+ style='max-width: 350px; margin: auto; border-radius: 20px; box-shadow: 0 8px 16px rgba(0,0,0,0.1);' />
115
+ </div>
116
+ """
117
+ )
118
+ with gr.Row():
119
+ with gr.Column():
120
+ with gr.Accordion("How do I get my chat file?", open=False):
121
+ gr.Markdown("""
122
+ ### Exporting your WhatsApp Chat
123
+ 1. **On your phone**, open the WhatsApp chat you want to analyze.
124
+ 2. Tap the **three dots** (⋮) in the top-right corner.
125
+ 3. Select **More** > **Export chat**.
126
+ 4. Choose **Without media**. This will create a smaller `.txt` file.
127
+ 5. Save the file to your phone or email it to yourself to access it on your computer.
128
+ 6. For more details, visit the [official WhatsApp Help Center](https://faq.whatsapp.com/1180414079177245/).
129
+ """)
130
+ gr.Markdown("### 1. Upload Your Chat File")
131
+ chat_file_upload = gr.File(label="Upload WhatsApp/Telegram .txt Export")
132
+ with gr.Column():
133
+ gr.Markdown("### 2. Customize Parameters")
134
+ context_slider = gr.Slider(500, 20000, value=5000, step=500, label="Context Window Size (Characters)")
135
+ temp_slider = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature (Creativity)")
136
+ lets_chat_button = gr.Button("💬 Start Chatting 💬", variant="primary")
137
+
138
+ with gr.Column(visible=False) as chat_page:
139
+ gr.Markdown("<h1 style='text-align: center;'>Chat Analyzer</h1>")
140
+ chatbot_ui = gr.Chatbot(height=600, bubble_full_width=False)
141
+ with gr.Row():
142
+ user_input_box = gr.Textbox(placeholder="Ask a question about your chat...", scale=5)
143
+ submit_button = gr.Button("Send", variant="primary", scale=1)
144
+
145
+ def go_to_chat(current_state, chat_file, context_size, temperature):
146
+ if chat_file is None:
147
+ raise gr.Error("A chat file must be uploaded.")
148
+ with open(chat_file.name, 'r', encoding='utf-8') as f:
149
+ content = f.read()
150
+ parsed_content = parse_chat_file(content)
151
+ if "Could not parse" in parsed_content:
152
+ raise gr.Error("Failed to parse the chat file. Please check the format.")
153
+ new_state = {
154
+ "chat_content": parsed_content,
155
+ "context_size": context_size,
156
+ "temperature": temperature,
157
+ }
158
+ return (
159
+ new_state,
160
+ gr.Column(visible=False),
161
+ gr.Column(visible=True)
162
+ )
163
+
164
+ lets_chat_button.click(
165
+ fn=go_to_chat,
166
+ inputs=[app_state, chat_file_upload, context_slider, temp_slider],
167
+ outputs=[app_state, welcome_page, chat_page]
168
+ )
169
+ submit_button.click(
170
+ fn=process_chat_request,
171
+ inputs=[user_input_box, chatbot_ui, app_state],
172
+ outputs=[user_input_box, chatbot_ui]
173
+ )
174
+ user_input_box.submit(
175
+ fn=process_chat_request,
176
+ inputs=[user_input_box, chatbot_ui, app_state],
177
+ outputs=[user_input_box, chatbot_ui]
178
+ )
179
+
180
+ if __name__ == "__main__":
181
+ demo.launch()