khurrameycon commited on
Commit
e8ef368
·
verified ·
1 Parent(s): 1ed7eae

flask - from gradio to flask

Browse files
Files changed (1) hide show
  1. app.py +55 -18
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import gradio as gr
2
  import os
3
  import torch
4
  from transformers import AutoProcessor, MllamaForConditionalGeneration, TextIteratorStreamer
@@ -8,6 +8,7 @@ import tempfile
8
  import requests
9
  from PyPDF2 import PdfReader
10
  from threading import Thread
 
11
 
12
  # Check if we're running in a Hugging Face Space and if SPACES_ZERO_GPU is enabled
13
  # IS_SPACES_ZERO = os.environ.get("SPACES_ZERO_GPU", "0") == "1"
@@ -20,6 +21,8 @@ LOW_MEMORY = os.getenv("LOW_MEMORY", "0") == "1"
20
  print(f"Using device: {device}")
21
  print(f"Low memory mode: {LOW_MEMORY}")
22
 
 
 
23
  # Get Hugging Face token from environment variables
24
  HF_TOKEN = os.environ.get('HF_TOKEN')
25
 
@@ -79,9 +82,11 @@ def extract_text_from_pdf(pdf_url):
79
  # raise HTTPException(status_code=400, detail=f"Error extracting text from PDF: {str(e)}")
80
 
81
  @spaces.GPU
82
- def predict_text(text, url = 'https://arinsight.co/2024_FA_AEC_1200_GR1_GR2.pdf'):
83
- pdf_text = extract_text_from_pdf('https://arinsight.co/2024_FA_AEC_1200_GR1_GR2.pdf')
84
- text_combined = text + "\n\nExtracted Text from PDF:\n" + pdf_text
 
 
85
  # Prepare the input messages
86
  messages = [{"role": "user", "content": [{"type": "text", "text": text_combined}]}]
87
 
@@ -100,7 +105,7 @@ def predict_text(text, url = 'https://arinsight.co/2024_FA_AEC_1200_GR1_GR2.pdf'
100
 
101
  streamer = TextIteratorStreamer(processor, skip_special_tokens=True, skip_prompt=True)
102
 
103
- generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
104
  generated_text = ""
105
 
106
  thread = Thread(target=model.generate, kwargs=generation_kwargs)
@@ -116,18 +121,50 @@ def predict_text(text, url = 'https://arinsight.co/2024_FA_AEC_1200_GR1_GR2.pdf'
116
  return buffer
117
 
118
 
119
- # Define the Gradio interface
120
- interface = gr.Interface(
121
- fn=predict_text,
122
- inputs=[
123
- # gr.Image(type="pil", label="Image Input"), # Image input with label
124
- gr.Textbox(label="Text Input") # Textbox input with label
125
- ],
126
- outputs=gr.Textbox(label="Generated Response"), # Output with a more descriptive label
127
- title="Llama 3.2 11B Vision Instruct Demo", # Title of the interface
128
- description="This demo uses Meta's Llama 3.2 11B Vision model to generate responses based on an image and text input.", # Short description
129
- theme="compact" # Using a compact theme for a cleaner look
130
  )
131
 
132
- # Launch the interface
133
- interface.launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import gradio as gr
2
  import os
3
  import torch
4
  from transformers import AutoProcessor, MllamaForConditionalGeneration, TextIteratorStreamer
 
8
  import requests
9
  from PyPDF2 import PdfReader
10
  from threading import Thread
11
+ from flask import Flask, request, jsonify
12
 
13
  # Check if we're running in a Hugging Face Space and if SPACES_ZERO_GPU is enabled
14
  # IS_SPACES_ZERO = os.environ.get("SPACES_ZERO_GPU", "0") == "1"
 
21
  print(f"Using device: {device}")
22
  print(f"Low memory mode: {LOW_MEMORY}")
23
 
24
+ app = Flask(__name__)
25
+
26
  # Get Hugging Face token from environment variables
27
  HF_TOKEN = os.environ.get('HF_TOKEN')
28
 
 
82
  # raise HTTPException(status_code=400, detail=f"Error extracting text from PDF: {str(e)}")
83
 
84
  @spaces.GPU
85
+ def predict_text(text):
86
+ # pdf_text = extract_text_from_pdf('https://arinsight.co/2024_FA_AEC_1200_GR1_GR2.pdf')
87
+
88
+ text_combined = text # + "\n\nExtracted Text from PDF:\n" + pdf_text
89
+
90
  # Prepare the input messages
91
  messages = [{"role": "user", "content": [{"type": "text", "text": text_combined}]}]
92
 
 
105
 
106
  streamer = TextIteratorStreamer(processor, skip_special_tokens=True, skip_prompt=True)
107
 
108
+ generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=2048)
109
  generated_text = ""
110
 
111
  thread = Thread(target=model.generate, kwargs=generation_kwargs)
 
121
  return buffer
122
 
123
 
124
+ PROMPT = (
125
+ "Extract the following information from the provided text ONLY "
126
+ "Course Code, Course Name, Credit, Delivery method, Course description, and Topical outline and do not add anything else except the information available in this text. "
 
 
 
 
 
 
 
 
127
  )
128
 
129
+ @app.route("/", methods=["GET"])
130
+ def home():
131
+ return jsonify({"message": "Welcome to the PDF Extraction API. Use the /extract endpoint to extract information."})
132
+
133
+ @app.route("/favicon.ico")
134
+ def favicon():
135
+ return "", 204
136
+
137
+ @app.route("/extract", methods=["POST"])
138
+ def extract_info():
139
+ data = request.json
140
+ if not data or "url" not in data:
141
+ return jsonify({"error": "Please provide a PDF URL in the request body."}), 400
142
+
143
+ pdf_url = data["url"]
144
+ try:
145
+ pdf_text = extract_text_from_pdf(pdf_url)
146
+ prompt = f"{PROMPT}\n\n{pdf_text}"
147
+ response = predict_text(prompt)
148
+ return jsonify({"extracted_info": response})
149
+ except Exception as e:
150
+ return jsonify({"error": str(e)}), 500
151
+
152
+ if __name__ == "__main__":
153
+ app.run(host="0.0.0.0", port=7860)
154
+
155
+
156
+ # # Define the Gradio interface
157
+ # interface = gr.Interface(
158
+ # fn=predict_text,
159
+ # inputs=[
160
+ # # gr.Image(type="pil", label="Image Input"), # Image input with label
161
+ # gr.Textbox(label="Text Input") # Textbox input with label
162
+ # ],
163
+ # outputs=gr.Textbox(label="Generated Response"), # Output with a more descriptive label
164
+ # title="Llama 3.2 11B Vision Instruct Demo", # Title of the interface
165
+ # description="This demo uses Meta's Llama 3.2 11B Vision model to generate responses based on an image and text input.", # Short description
166
+ # theme="compact" # Using a compact theme for a cleaner look
167
+ # )
168
+
169
+ # # Launch the interface
170
+ # interface.launch(debug=True)