File size: 11,266 Bytes
14ea8fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import gradio as gr
import PyPDF2
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from deep_translator import GoogleTranslator  # More stable than googletrans
import logging
from typing import Optional, Dict
import time
from pathlib import Path
import os
import pandas as pd

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Language mapping with detailed descriptions
LANGUAGE_MAPPING = {
    "hi": {
        "name": "Hindi - हिन्दी",
        "description": "Official language of India, written in Devanagari script",
        "deep_translator_code": "hi"
    },
    "ta": {
        "name": "Tamil - தமிழ்",
        "description": "Classical language of Tamil Nadu, written in Tamil script",
        "deep_translator_code": "ta"
    },
    "te": {
        "name": "Telugu - తెలుగు",
        "description": "Official language of Andhra Pradesh and Telangana",
        "deep_translator_code": "te"
    },
    "bn": {
        "name": "Bengali - বাংলা",
        "description": "Official language of West Bengal and Bangladesh",
        "deep_translator_code": "bn"
    },
    "mr": {
        "name": "Marathi - मराठी",
        "description": "Official language of Maharashtra",
        "deep_translator_code": "mr"
    }
}

class FileQueryTranslator:
    def __init__(self, max_retries=3, retry_delay=1):
        self.max_retries = max_retries
        self.retry_delay = retry_delay
        self.setup_device()
        self.setup_model()
        logger.info(f"Initialization complete. Using device: {self.device}")

    def setup_device(self):
        """Setup CUDA device with error handling"""
        try:
            self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
            if self.device.type == "cuda":
                # Check CUDA memory
                torch.cuda.empty_cache()
                logger.info(f"Available CUDA memory: {torch.cuda.get_device_properties(0).total_memory}")
        except Exception as e:
            logger.warning(f"Error setting up CUDA device: {e}. Falling back to CPU.")
            self.device = torch.device("cpu")

    def setup_model(self):
        """Initialize the model with retry mechanism"""
        for attempt in range(self.max_retries):
            try:
                model_name = "facebook/opt-125m"  # Using smaller model for stability
                self.tokenizer = AutoTokenizer.from_pretrained(model_name)
                self.model = AutoModelForCausalLM.from_pretrained(
                    model_name,
                    torch_dtype=torch.float16 if self.device.type == "cuda" else torch.float32
                )
                
                if self.device.type == "cuda":
                    self.model = self.model.to(self.device)
                    torch.cuda.empty_cache()  # Clear CUDA cache
                else:
                    self.model = self.model.to(self.device)
                
                logger.info(f"Model loaded successfully on {self.device}")
                break
            except Exception as e:
                logger.error(f"Attempt {attempt + 1} failed: {str(e)}")
                if attempt < self.max_retries - 1:
                    time.sleep(self.retry_delay)
                else:
                    raise Exception("Failed to load model after maximum retries")

    def extract_text_from_pdf(self, pdf_file: str) -> str:
        """Extract text from PDF with robust error handling"""
        try:
            if not os.path.exists(pdf_file):
                raise FileNotFoundError(f"PDF file not found: {pdf_file}")
            
            pdf_reader = PyPDF2.PdfReader(pdf_file)
            text = []
            
            for page_num in range(len(pdf_reader.pages)):
                try:
                    page = pdf_reader.pages[page_num]
                    text.append(page.extract_text())
                except Exception as e:
                    logger.error(f"Error extracting text from page {page_num}: {e}")
                    text.append(f"[Error extracting page {page_num}]")
            
            return "\n".join(text)
        except Exception as e:
            logger.error(f"Error processing PDF: {str(e)}")
            return f"Error processing PDF: {str(e)}"

    def extract_text_from_csv(self, csv_file: str) -> str:
        """Extract text from CSV with robust error handling"""
        try:
            if not os.path.exists(csv_file):
                raise FileNotFoundError(f"CSV file not found: {csv_file}")
            
            df = pd.read_csv(csv_file)
            text = df.to_string(index=False)
            
            return text
        except Exception as e:
            logger.error(f"Error processing CSV: {str(e)}")
            return f"Error processing CSV: {str(e)}"

    def extract_text_from_xlsx(self, xlsx_file: str) -> str:
        """Extract text from XLSX with robust error handling"""
        try:
            if not os.path.exists(xlsx_file):
                raise FileNotFoundError(f"XLSX file not found: {xlsx_file}")
            
            df = pd.read_excel(xlsx_file)
            text = df.to_string(index=False)
            
            return text
        except Exception as e:
            logger.error(f"Error processing XLSX: {str(e)}")
            return f"Error processing XLSX: {str(e)}"

    def translate_text(self, text: str, target_lang: str) -> str:
        """Translate text using deep_translator with retry mechanism"""
        for attempt in range(self.max_retries):
            try:
                translator = GoogleTranslator(source='auto', target=target_lang)
                
                # Split text into chunks if it's too long (Google Translate limit)
                max_chunk_size = 4500
                chunks = [text[i:i + max_chunk_size] for i in range(0, len(text), max_chunk_size)]
                
                translated_chunks = []
                for chunk in chunks:
                    translated_chunk = translator.translate(chunk)
                    translated_chunks.append(translated_chunk)
                    time.sleep(0.5)  # Rate limiting
                
                return ' '.join(translated_chunks)
            except Exception as e:
                logger.error(f"Translation attempt {attempt + 1} failed: {str(e)}")
                if attempt < self.max_retries - 1:
                    time.sleep(self.retry_delay)
                else:
                    return f"Translation error: {str(e)}"

    def process_query(self, file_path: str, file_type: str, query: str, language: str) -> str:
        """Process query with comprehensive error handling"""
        try:
            # Validate inputs
            if not file_path or not os.path.exists(file_path):
                return "Please provide a valid file."
            if not query.strip():
                return "Please provide a valid query."
            if language not in LANGUAGE_MAPPING:
                return "Please select a valid language."

            # Extract text based on file type
            if file_type == "pdf":
                file_text = self.extract_text_from_pdf(file_path)
            elif file_type == "csv":
                file_text = self.extract_text_from_csv(file_path)
            elif file_type == "xlsx":
                file_text = self.extract_text_from_xlsx(file_path)
            else:
                return "Unsupported file type."

            if file_text.startswith("Error"):
                return file_text

            # Generate response
            prompt = f"Query: {query}\n\nContent: {file_text[:1000]}\n\nAnswer:"  # Limit content length
            
            input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to(self.device)
            with torch.no_grad():
                output = self.model.generate(
                    input_ids,
                    max_new_tokens=200,  # Use max_new_tokens instead of max_length
                    num_return_sequences=1,
                    temperature=0.7,
                    pad_token_id=self.tokenizer.eos_token_id
                )
            response = self.tokenizer.decode(output[0], skip_special_tokens=True)

            # Translate
            target_lang = LANGUAGE_MAPPING[language]["deep_translator_code"]
            translated_response = self.translate_text(response, target_lang)
            
            return translated_response

        except Exception as e:
            logger.error(f"Error in process_query: {str(e)}")
            return f"An error occurred: {str(e)}"

# Gradio interface
def create_interface():
    file_processor = FileQueryTranslator()

    with gr.Blocks() as demo:
        gr.Markdown("### File Query and Translation System")
        
        with gr.Row():
            with gr.Column():
                file_input = gr.File(
                    label="Upload File (PDF, CSV, XLSX)",
                    type="filepath"
                )
                file_type_input = gr.Radio(
                    label="Select File Type",
                    choices=["pdf", "csv", "xlsx"],
                    value="pdf"
                )
                query_input = gr.Textbox(
                    label="Enter your question about the file",
                    placeholder="What would you like to know about the document?"
                )
                language_input = gr.Dropdown(
                    label="Select Output Language",
                    choices=[f"{code} - {info['name']}" for code, info in LANGUAGE_MAPPING.items()],
                    value="hi - Hindi - हिन्दी"
                )
                language_description = gr.Textbox(
                    label="Language Information",
                    value=LANGUAGE_MAPPING['hi']['description'],
                    interactive=False
                )

        with gr.Row():
            output_text = gr.Textbox(
                label="Translated Answer",
                placeholder="Translation will appear here...",
                lines=5
            )

        def update_description(selected):
            code = selected.split(" - ")[0]
            return LANGUAGE_MAPPING[code]['description']

        def process_and_translate(file_path, file_type, query, language):
            try:
                lang_code = language.split(" - ")[0]
                return file_processor.process_query(file_path, file_type, query, lang_code)
            except Exception as e:
                return f"Error processing request: {str(e)}"

        # Event handlers
        language_input.change(
            fn=update_description,
            inputs=[language_input],
            outputs=[language_description]
        )

        submit_button = gr.Button("Get Answer")
        submit_button.click(
            fn=process_and_translate,
            inputs=[file_input, file_type_input, query_input, language_input],
            outputs=output_text
        )

    return demo

if __name__ == "__main__":
    demo = create_interface()
    demo.queue()  # Enable queueing
    demo.launch(share=True)