Polarisailabs commited on
Commit
c5590b8
·
verified ·
1 Parent(s): f6d8ac1

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -183
app.py CHANGED
@@ -1,184 +1,45 @@
1
- import os
2
- import gradio as gr
 
 
 
 
 
 
 
3
  from openai import OpenAI
4
-
5
- API_KEY = os.environ['API_KEY']
6
- # Initialize client
7
- client = OpenAI(
8
- base_url="https://openrouter.ai/api/v1",
9
- api_key=API_KEY
10
- )
11
-
12
- def classify_text(text, classification_type="sentiment", custom_labels=""):
13
- """
14
- Classify text using OpenRouter's GPT-OSS-20B model
15
- """
16
- if not text.strip():
17
- return "Please enter some text to classify."
18
-
19
- # Define classification prompts based on type
20
- if classification_type == "Sentiment":
21
- prompt = f"Classify the sentiment of the following text as Positive, Negative, or Neutral. Only respond with one word: Positive, Negative, or Neutral.\n\nText: {text}"
22
- # elif classification_type == "topic":
23
- # prompt = f"Classify the main topic/category of the following text. Choose the most appropriate category and respond with just the category name.\n\nText: {text}"
24
- elif classification_type == "Spam":
25
- prompt = f"Classify whether the following text is Spam or Not Spam. Only respond with: Spam or Not Spam.\n\nText: {text}"
26
- # elif classification_type == "custom":
27
- # if not custom_labels.strip():
28
- # return "Please provide custom labels for classification."
29
- # prompt = f"Classify the following text into one of these categories: {custom_labels}. Only respond with one of the provided categories.\n\nText: {text}"
30
- # else:
31
- # prompt = f"Classify the following text and provide a brief classification result.\n\nText: {text}"
32
-
33
- try:
34
- response = client.chat.completions.create(
35
- model="openai/gpt-oss-20b",
36
- messages=[
37
- {"role": "system", "content": "You are a text classification assistant. Provide concise, accurate classifications."},
38
- {"role": "user", "content": prompt}
39
- ],
40
- max_tokens=50,
41
- temperature=0.1,
42
- extra_headers={
43
- "Authorization": f"Bearer {API_KEY}",
44
- "HTTP-Referer": "https://your-app-url.com",
45
- "X-Title": ""
46
- }
47
- )
48
-
49
- classification_result = response.choices[0].message.content.strip()
50
- return f"Classification Result: {classification_result}"
51
-
52
- except Exception as e:
53
- return f"Error: {str(e)}"
54
-
55
- def batch_classify(file, classification_type="sentiment", custom_labels=""):
56
- """
57
- Classify multiple texts from uploaded file
58
- """
59
- if file is None:
60
- return "Please upload a text file."
61
-
62
- try:
63
- # Read file content
64
- with open(file.name, 'r', encoding='utf-8') as f:
65
- lines = f.readlines()
66
-
67
- results = []
68
- for i, line in enumerate(lines[:10], 1): # Limit to first 10 lines
69
- line = line.strip()
70
- if line:
71
- result = classify_text(line, classification_type, custom_labels)
72
- results.append(f"{i}. **Text:** {line}\n **Result:** {result}\n")
73
-
74
- return "\n".join(results) if results else "No text found in file."
75
-
76
- except Exception as e:
77
- return f"Error processing file: {str(e)}"
78
-
79
- # Create Gradio interface
80
- with gr.Blocks(
81
- title="",
82
- #theme=gr.themes.Soft()
83
- theme=gr.themes.Default(primary_hue="sky")
84
-
85
- ) as demo:
86
- with gr.Tabs():
87
- # Single Text Classification Tab
88
- with gr.Tab("Single Text"):
89
- with gr.Row():
90
- with gr.Column(scale=2):
91
- text_input = gr.Textbox(
92
- label="",
93
- placeholder="Enter text to classify...",
94
- lines=4
95
- )
96
-
97
- classification_type = gr.Radio(
98
- choices=["Sentiment", "Spam"],
99
- value="Sentiment",
100
- label="Classification Type:"
101
- )
102
-
103
- custom_labels = gr.Textbox(
104
- label="Custom Labels (for custom classification)",
105
- placeholder="e.g., business, technology, sports, entertainment",
106
- visible=False
107
- )
108
-
109
- classify_btn = gr.Button("Classify Text", variant="primary")
110
-
111
- with gr.Column(scale=2):
112
- single_output = gr.Markdown(
113
- value=""
114
- )
115
-
116
- # Show/hide custom labels based on selection
117
- def toggle_custom_labels(choice):
118
- return gr.update(visible=(choice == "custom"))
119
-
120
- classification_type.change(
121
- toggle_custom_labels,
122
- inputs=[classification_type],
123
- outputs=[custom_labels]
124
- )
125
-
126
- classify_btn.click(
127
- classify_text,
128
- inputs=[text_input, classification_type, custom_labels],
129
- outputs=[single_output]
130
- )
131
-
132
- # Batch Classification Tab
133
- with gr.Tab("Batch Classification"):
134
- with gr.Row():
135
- with gr.Column(scale=2):
136
- gr.Markdown("Upload a text or csv file:")
137
-
138
- file_input = gr.File(
139
- label="Upload File",
140
- file_types=[".txt", ".csv"]
141
- )
142
-
143
- batch_classification_type = gr.Radio(
144
- choices=["Sentiment", "Spam"],
145
- value="Sentiment",
146
- label="Classification Type:"
147
- )
148
-
149
- batch_custom_labels = gr.Textbox(
150
- label="Custom Labels (for custom classification)",
151
- placeholder="e.g., business, technology, sports, entertainment",
152
- visible=False
153
- )
154
-
155
- batch_classify_btn = gr.Button("🔍 Classify Batch", variant="primary")
156
-
157
- with gr.Column(scale=2):
158
- batch_output = gr.Markdown(
159
- value=""
160
- )
161
-
162
- def toggle_batch_custom_labels(choice):
163
- return gr.update(visible=(choice == "custom"))
164
-
165
- batch_classification_type.change(
166
- toggle_batch_custom_labels,
167
- inputs=[batch_classification_type],
168
- outputs=[batch_custom_labels]
169
- )
170
-
171
- batch_classify_btn.click(
172
- batch_classify,
173
- inputs=[file_input, batch_classification_type, batch_custom_labels],
174
- outputs=[batch_output]
175
- )
176
-
177
- # Launch the app
178
- if __name__ == "__main__":
179
- demo.launch(
180
- server_name="0.0.0.0",
181
- server_port=7860,
182
- share=True,
183
- show_error=True
184
- )
 
1
+ _H='custom'
2
+ _G='primary'
3
+ _F='e.g., business, technology, sports, entertainment'
4
+ _E='Custom Labels (for custom classification)'
5
+ _D='Classification Type:'
6
+ _C='sentiment'
7
+ _B='Spam'
8
+ _A='Sentiment'
9
+ import os,gradio as gr
10
  from openai import OpenAI
11
+ API_KEY=os.environ['API_KEY']
12
+ client=OpenAI(base_url='https://openrouter.ai/api/v1',api_key=API_KEY)
13
+ def classify_text(text,classification_type=_C,custom_labels=''):
14
+ "\n Classify text using OpenRouter's GPT-OSS-20B model\n ";E='content';D='role';B=classification_type;A=text
15
+ if not A.strip():return'Please enter some text to classify.'
16
+ if B==_A:C=f"Classify the sentiment of the following text as Positive, Negative, or Neutral. Only respond with one word: Positive, Negative, or Neutral.\n\nText: {A}"
17
+ elif B==_B:C=f"Classify whether the following text is Spam or Not Spam. Only respond with: Spam or Not Spam.\n\nText: {A}"
18
+ try:F=client.chat.completions.create(model='openai/gpt-oss-20b',messages=[{D:'system',E:'You are a text classification assistant. Provide concise, accurate classifications.'},{D:'user',E:C}],max_tokens=50,temperature=.1,extra_headers={'Authorization':f"Bearer {API_KEY}",'HTTP-Referer':'https://your-app-url.com','X-Title':''});G=F.choices[0].message.content.strip();return f"Classification Result: {G}"
19
+ except Exception as H:return f"Error: {str(H)}"
20
+ def batch_classify(file,classification_type=_C,custom_labels=''):
21
+ '\n Classify multiple texts from uploaded file\n '
22
+ if file is None:return'Please upload a text file.'
23
+ try:
24
+ with open(file.name,'r',encoding='utf-8')as C:D=C.readlines()
25
+ B=[]
26
+ for(E,A)in enumerate(D[:10],1):
27
+ A=A.strip()
28
+ if A:F=classify_text(A,classification_type,custom_labels);B.append(f"{E}. **Text:** {A}\n **Result:** {F}\n")
29
+ return'\n'.join(B)if B else'No text found in file.'
30
+ except Exception as G:return f"Error processing file: {str(G)}"
31
+ with gr.Blocks(title='',theme=gr.themes.Default(primary_hue='sky'))as demo:
32
+ with gr.Tabs():
33
+ with gr.Tab('Single Text'):
34
+ with gr.Row():
35
+ with gr.Column(scale=2):text_input=gr.Textbox(label='',placeholder='Enter text to classify...',lines=4);classification_type=gr.Radio(choices=[_A,_B],value=_A,label=_D);custom_labels=gr.Textbox(label=_E,placeholder=_F,visible=False);classify_btn=gr.Button('Classify Text',variant=_G)
36
+ with gr.Column(scale=2):single_output=gr.Markdown(value='')
37
+ def toggle_custom_labels(choice):return gr.update(visible=choice==_H)
38
+ classification_type.change(toggle_custom_labels,inputs=[classification_type],outputs=[custom_labels]);classify_btn.click(classify_text,inputs=[text_input,classification_type,custom_labels],outputs=[single_output])
39
+ with gr.Tab('Batch Classification'):
40
+ with gr.Row():
41
+ with gr.Column(scale=2):gr.Markdown('Upload a text or csv file:');file_input=gr.File(label='Upload File',file_types=['.txt','.csv']);batch_classification_type=gr.Radio(choices=[_A,_B],value=_A,label=_D);batch_custom_labels=gr.Textbox(label=_E,placeholder=_F,visible=False);batch_classify_btn=gr.Button('🔍 Classify Batch',variant=_G)
42
+ with gr.Column(scale=2):batch_output=gr.Markdown(value='')
43
+ def toggle_batch_custom_labels(choice):return gr.update(visible=choice==_H)
44
+ batch_classification_type.change(toggle_batch_custom_labels,inputs=[batch_classification_type],outputs=[batch_custom_labels]);batch_classify_btn.click(batch_classify,inputs=[file_input,batch_classification_type,batch_custom_labels],outputs=[batch_output])
45
+ if __name__=='__main__':demo.launch(server_name='0.0.0.0',server_port=7860,share=True,show_error=True)