AsthanM commited on
Commit
dbf8b00
Β·
verified Β·
1 Parent(s): a1ed08e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -0
app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import google.generativeai as genai
4
+ import chardet # Auto-detect file encoding
5
+
6
+ # βœ… Load API Key securely from Hugging Face Secrets
7
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
8
+
9
+ if not GOOGLE_API_KEY:
10
+ raise ValueError("⚠ Error: Google API Key is missing. Set it in Hugging Face Secrets.")
11
+
12
+ # βœ… Configure Google Generative AI (Gemini)
13
+ genai.configure(api_key=GOOGLE_API_KEY)
14
+
15
+ # βœ… Load the Gemini Model
16
+ model = genai.GenerativeModel(model_name="models/gemini-2.0-flash")
17
+
18
+ # πŸ”Ή Function to read a file with auto-detected encoding
19
+ def read_file_with_encoding(file_path):
20
+ try:
21
+ with open(file_path, "rb") as f:
22
+ raw_data = f.read()
23
+
24
+ # Detect file encoding
25
+ encoding = chardet.detect(raw_data)["encoding"]
26
+ if encoding is None:
27
+ encoding = "utf-8" # Default to UTF-8 if detection fails
28
+
29
+ # Read file with detected encoding
30
+ with open(file_path, "r", encoding=encoding, errors="replace") as f:
31
+ return f.read()
32
+ except Exception as e:
33
+ return f"⚠ Error reading file: {str(e)}"
34
+
35
+ # πŸ”Ή Function to analyze text or file content
36
+ def analyze_input(text, file):
37
+ try:
38
+ if file is not None:
39
+ text = read_file_with_encoding(file) # βœ… Auto-detect encoding
40
+ elif not text.strip():
41
+ return "⚠ Error: Please enter text or upload a file.", ""
42
+
43
+ text = text[:2000] # Limit input text size
44
+ prompt = f"Analyze and summarize this document:\n\n{text}"
45
+ response = model.generate_content([prompt], stream=True) # βœ… Fix applied
46
+
47
+ # Collect streamed response
48
+ result = "".join([chunk.text for chunk in response])
49
+ word_count = len(text.split())
50
+
51
+ return result, f"πŸ“Š Word Count: {word_count}"
52
+ except Exception as e:
53
+ return f"⚠ Error: {str(e)}", ""
54
+
55
+ # πŸ”Ή Function to clear inputs and outputs
56
+ def clear_inputs():
57
+ return "", None, "", "", None
58
+
59
+ # πŸ”Ή Function to generate a downloadable text file
60
+ def generate_downloadable_file(text):
61
+ if text.strip():
62
+ file_path = "analysis_result.txt"
63
+ with open(file_path, "w", encoding="utf-8") as f:
64
+ f.write(text)
65
+ return file_path
66
+ else:
67
+ return None
68
+
69
+ # βœ… Create Gradio UI
70
+ with gr.Blocks(theme=gr.themes.Default()) as demo:
71
+ gr.Markdown("""
72
+ # πŸ“„ *AI-Powered Text & File Analyzer*
73
+ πŸš€ Upload a .txt file or enter text manually to get an AI-generated analysis and summary.
74
+ """)
75
+
76
+ with gr.Row():
77
+ text_input = gr.Textbox(label="✍ Enter Text", placeholder="Type or paste your text here...", lines=6)
78
+ file_input = gr.File(label="πŸ“‚ Upload Text File (.txt)", type="filepath")
79
+
80
+ output_text = gr.Textbox(label="πŸ“ Analysis Result", lines=10, interactive=False)
81
+ word_count_display = gr.Textbox(label="πŸ“Š Word Count", interactive=False)
82
+
83
+ with gr.Row():
84
+ analyze_button = gr.Button("πŸ” Analyze", variant="primary")
85
+ clear_button = gr.Button("πŸ—‘ Clear", variant="secondary")
86
+
87
+ with gr.Column():
88
+ gr.Markdown("### πŸ“₯ Download Analysis Result")
89
+ with gr.Row():
90
+ download_button = gr.Button("⬇ Download Result", variant="success", size="sm")
91
+ download_file = gr.File(label="πŸ“„ Click to Download", interactive=False)
92
+
93
+ # βœ… Button functionalities
94
+ analyze_button.click(analyze_input, inputs=[text_input, file_input], outputs=[output_text, word_count_display])
95
+ clear_button.click(clear_inputs, inputs=[], outputs=[text_input, file_input, output_text, word_count_display, download_file])
96
+ download_button.click(generate_downloadable_file, inputs=output_text, outputs=download_file)
97
+
98
+ # βœ… Launch the Gradio app
99
+ demo.launch()