IAMTFRMZA commited on
Commit
73936e5
·
verified ·
1 Parent(s): e40be04

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -59
app.py CHANGED
@@ -1,63 +1,104 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  )
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- if __name__ == "__main__":
63
- demo.launch()
 
1
  import gradio as gr
2
+ from transformers import LLaMAForConditionalGeneration, LLaMATokenizer
3
+ import torch
4
+ import pandas as pd
5
+ from PyPDF2 import PdfFileReader
6
+ from googleapiclient.discovery import build
7
+ from google_auth_oauthlib.flow import InstalledAppFlow
8
+ from google.auth.transport.requests import Request
9
+ import pickle
10
+ import pydub
11
+
12
+ # Set up LLaMA model and tokenizer
13
+ model = LLaMAForConditionalGeneration.from_pretrained("facebook/llama-3.1-base")
14
+ tokenizer = LLaMATokenizer.from_pretrained("facebook/llama-3.1-base")
15
+
16
+ # Set up Google API credentials
17
+ SCOPES = ['https://www.googleapis.com/auth/drive']
18
+ creds = None
19
+ if creds is None or not creds.valid:
20
+ if creds and creds.expired and creds.refresh_token:
21
+ creds.refresh(Request())
22
+ else:
23
+ flow = InstalledAppFlow.from_client_secrets_file(
24
+ 'credentials.json', SCOPES)
25
+ creds = flow.run_local_server(port=0)
26
+ drive_service = build('drive', 'v3', credentials=creds)
27
+
28
+ # Define function to process uploaded files
29
+ def process_file(file):
30
+ if file.name.endswith('.pdf'):
31
+ pdf_file = PdfFileReader(file)
32
+ text = ''
33
+ for page in range(pdf_file.numPages):
34
+ text += pdf_file.getPage(page).extractText()
35
+ return text
36
+ elif file.name.endswith('.csv') or file.name.endswith('.xlsx'):
37
+ if file.name.endswith('.csv'):
38
+ df = pd.read_csv(file)
39
+ else:
40
+ df = pd.read_excel(file)
41
+ return str(df)
42
+ elif file.name.endswith('.docx'):
43
+ # You need to implement a function to extract text from Word documents
44
+ # For simplicity, this example just returns an error message
45
+ return "Error: Word document support not implemented"
46
+ elif file.name.endswith('.gsheet'):
47
+ spreadsheet_id = file.name.split('/')[-1]
48
+ range_name = 'Sheet1!A1:Z1000' # You can change this range as needed
49
+ service = build('sheets', 'v4', credentials=creds)
50
+ sheet = service.spreadsheets()
51
+ result = sheet.values().get(spreadsheetId=spreadsheet_id,
52
+ range=range_name).execute()
53
+ values = result.get('values', [])
54
+ return str(values)
55
+ elif file.name.endswith('.gdoc'):
56
+ document_id = file.name.split('/')[-1]
57
+ service = build('docs', 'v1', credentials=creds)
58
+ doc = service.documents().get(documentId=document_id).execute()
59
+ text = ''
60
+ for element in doc.get('body').get('content'):
61
+ if 'paragraph' in element:
62
+ text += element.get('paragraph').get('elements')[0].get('textRun').get('content')
63
+ return text
64
+ elif file.name.endswith('.mp3'):
65
+ audio = pydub.AudioSegment.from_mp3(file)
66
+ text = ''
67
+ # You need to implement a function to transcribe audio
68
+ # For simplicity, this example just returns an error message
69
+ return "Error: Audio transcription support not implemented"
70
+ else:
71
+ return "Error: File type not supported"
72
+
73
+ # Define function to answer questions about the uploaded content
74
+ def answer_question(content, question):
75
+ inputs = tokenizer.encode(question, return_tensors="pt")
76
+ outputs = model.generate(inputs, max_length=100)
77
+ answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
78
+ return answer
79
+
80
+ # Create Gradio interface
81
+ demo = gr.Interface(
82
+ fn=answer_question,
83
+ inputs=["file", "text"],
84
+ outputs="text",
85
+ title="LLaMA Chatbot",
86
+ description="Upload a file or paste some text, and ask a question about the content.",
87
  )
88
 
89
+ # Define function to update the Gradio interface with the uploaded file's content
90
+ def update_interface(file):
91
+ content = process_file(file)
92
+ demo.update(inputs=[content])
93
+
94
+ # Create Gradio interface with file upload
95
+ demo_with_upload = gr.Interface(
96
+ fn=update_interface,
97
+ inputs=["file"],
98
+ outputs=None,
99
+ title="LLaMA Chatbot",
100
+ description="Upload a file to analyze its content.",
101
+ )
102
 
103
+ # Launch Gradio interface
104
+ demo_with_upload.launch()