ZeroTraceX commited on
Commit
376de8d
·
verified ·
1 Parent(s): 7e58bb5

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -173
app.py DELETED
@@ -1,173 +0,0 @@
1
- from flask import Flask, render_template, request, jsonify, Response
2
- from werkzeug.utils import secure_filename
3
- import os
4
- from huggingface_hub import InferenceClient
5
- import json
6
- import base64
7
- from io import BytesIO
8
- import tempfile
9
- from PIL import Image
10
- import pytesseract
11
- import fitz # PyMuPDF
12
- import uuid
13
-
14
- app = Flask(__name__)
15
- app.secret_key = 'your-secret-key-here'
16
-
17
- # Configuration
18
- app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
19
- ALLOWED_EXTENSIONS = {'pdf'}
20
-
21
- # Windows Configuration
22
- #TESSERACT_PATH = r"D:\Python-files\tesseract\tesseract.exe" # Update this path
23
- #pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
24
-
25
- # Store temporary file paths
26
- temp_files = {}
27
-
28
- def allowed_file(filename):
29
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
30
-
31
- @app.route('/')
32
- def index():
33
- return render_template('index.html')
34
-
35
- @app.route('/process_ai', methods=['POST'])
36
- def process_ai():
37
- try:
38
- text = request.json.get('text', '')
39
- image_data = request.json.get('image_data', None)
40
-
41
- def generate():
42
- client = InferenceClient()
43
-
44
- if image_data:
45
- # Process as image using chat completions
46
- messages = [
47
- {
48
- "role": "user",
49
- "content": [
50
- {
51
- "type": "text",
52
- "text": "Analyze the MCQ question and provide the question and correct answer and if u want to give explanation just give in 2 to 3 lines:"
53
- },
54
- {
55
- "type": "image_url",
56
- "image_url": {
57
- "url": f"data:image/jpeg;base64,{image_data}"
58
- }
59
- }
60
- ]
61
- }
62
- ]
63
-
64
- stream = client.chat.completions.create(
65
- model="meta-llama/Llama-3.2-11B-Vision-Instruct",
66
- messages=messages,
67
- max_tokens=500,
68
- stream=True
69
- )
70
- else:
71
- # Process as text using chat completions
72
- messages = [
73
- {
74
- "role": "user",
75
- "content": f"Analyze the MCQ question and provide the question and correct answer and if u want to give explanation just give in 2 to 3 lines:\n\n{text}"
76
- }
77
- ]
78
-
79
- stream = client.chat.completions.create(
80
- model="Qwen/Qwen2.5-Coder-32B-Instruct",
81
- messages=messages,
82
- max_tokens=500,
83
- stream=True
84
- )
85
-
86
- # Common streaming response handling for both text and image
87
- for chunk in stream:
88
- content = chunk.choices[0].delta.content
89
- if content:
90
- yield f'{{"chunk": {json.dumps(content)}}}\n'
91
-
92
- return Response(generate(), mimetype='application/x-ndjson')
93
- except Exception as e:
94
- return jsonify({'error': str(e)}), 500
95
-
96
- @app.route('/upload_pdf', methods=['POST', 'GET'])
97
- def upload_pdf():
98
- if request.method == 'POST':
99
- if 'file' not in request.files:
100
- return jsonify({'error': 'No file part'}), 400
101
-
102
- file = request.files['file']
103
- if file.filename == '' or not allowed_file(file.filename):
104
- return jsonify({'error': 'Invalid file'}), 400
105
-
106
- temp_pdf = None
107
- try:
108
- # Create a unique identifier for this upload
109
- file_id = str(uuid.uuid4())
110
-
111
- # Create a temporary file
112
- temp_pdf = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
113
- file.save(temp_pdf.name)
114
- temp_pdf.close()
115
-
116
- # Store the temp file path with its ID
117
- temp_files[file_id] = temp_pdf.name
118
-
119
- return jsonify({'success': True, 'message': 'File uploaded', 'file_id': file_id})
120
-
121
- except Exception as e:
122
- if temp_pdf:
123
- try:
124
- os.unlink(temp_pdf.name)
125
- except Exception as cleanup_error:
126
- print(f"Warning: Could not delete temporary file during error cleanup: {cleanup_error}")
127
- return jsonify({'error': str(e)}), 500
128
-
129
- elif request.method == 'GET':
130
- file_id = request.args.get('file_id')
131
- if not file_id or file_id not in temp_files:
132
- return jsonify({'error': 'No file to process'}), 400
133
-
134
- temp_pdf_path = temp_files[file_id]
135
-
136
- def generate():
137
- try:
138
- pdf_document = fitz.open(temp_pdf_path)
139
- total_pages = pdf_document.page_count
140
- texts = []
141
-
142
- for page_num in range(total_pages):
143
- page = pdf_document[page_num]
144
- pix = page.get_pixmap()
145
- img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
146
- text = pytesseract.image_to_string(img)
147
- texts.append(text)
148
-
149
- # Send progress update
150
- progress = ((page_num + 1) / total_pages) * 100
151
- yield f"data: {json.dumps({'progress': progress, 'page': page_num + 1, 'total': total_pages})}\n\n"
152
-
153
- # Send final result
154
- yield f"data: {json.dumps({'done': True, 'texts': texts})}\n\n"
155
-
156
- # Clean up
157
- pdf_document.close()
158
- os.unlink(temp_pdf_path)
159
- del temp_files[file_id]
160
-
161
- except Exception as e:
162
- print(f"Error during OCR: {e}")
163
- if 'pdf_document' in locals():
164
- pdf_document.close()
165
- try:
166
- os.unlink(temp_pdf_path)
167
- del temp_files[file_id]
168
- except:
169
- pass
170
- yield f"data: {json.dumps({'error': str(e)})}\n\n"
171
-
172
- return Response(generate(), mimetype='text/event-stream')
173
-