jina | 🔮 Build multimodal AI services | Machine Learning library
kandi X-RAY | jina Summary
Support
Quality
Security
License
Reuse
- Return an instance of FastAPI
- Get the full version of the module
- Details of the exception
- Return the exception code
- Get results from requests
- Yields all responses from a stream
- Return a sequence of Request objects
- Helper method to stream the requests
- Parse deployment arguments
- Fill an overloaded decorator
- Setup metrics
- Fill the docstring for an implementation
- Performs an async post request
- Add handlers to the logger
- Setup the server
- Performs a post request
- Setup the uvicorn server
- Write the workflow to a yaml file
- Parse the data into a BaseExecutor
- Start a running container
- Handle a request
- Creates a client
- Get results from the API
- Parse the arguments passed into the command line
- Perform a single request
- Convert a protobuf protobuf to a pydant model
jina Key Features
jina Examples and Code Snippets
python -m clip_server my.yml
cat my.yml | python -m clip_server -i
```yaml jtype: Flow version: '1' with: port: 51000 executors: - name: clip_t uses: jtype: CLIPEncoder metas: py_modules: - clip_server.executors.clip_torch ```
```yaml jtype: Flow version: '1' with: port: 51000 executors: - name: clip_o uses: jtype: CLIPEncoder metas: py_modules: - clip_server.executors.clip_onnx ```
```yaml jtype: Flow version: '1' with: port: 51000 executors: - name: clip_r uses: jtype: CLIPEncoder metas: py_modules: - clip_server.executors.clip_tensorrt ```
```{code-block} yaml --- emphasize-lines: 9 --- jtype: Flow version: '1' with: port: 51000 executors: - name: clip_t uses: jtype: CLIPEncoder with: metas: py_modules: - clip_server.executors.clip_torch ```
```{code-block} yaml --- emphasize-lines: 6 --- jtype: Flow version: '1' with: port: 51000 executors: - name: clip_t uses: jtype: CLIPEncoder with: metas: py_modules: - clip_server.executors.clip_torch ```
```{code-block} yaml --- emphasize-lines: 3,4 --- jtype: Flow version: '1' with: port: 51000 executors: - name: clip_t uses: jtype: CLIPEncoder with: metas: py_modules: - clip_server.executors.clip_torch ```
python -m clip_server search_flow.yml
```{code-block} yaml --- emphasize-lines: 9 --- jtype: Flow version: '1' with: port: 61000 executors: - name: encoder uses: jtype: CLIPEncoder metas: py_modules: - clip_server.executors.clip_torch - name: indexer uses: jtype: AnnLiteIndexer with: n_dim: 512 metas: py_modules: - annlite.executor workspace: './workspace' ```
```{code-block} yaml --- emphasize-lines: 17,18,19 --- jtype: Flow version: '1' with: port: 61000 executors: - name: encoder uses: jtype: CLIPEncoder with: metas: py_modules: - clip_server.executors.clip_torch - name: indexer uses: jtype: AnnLiteIndexer with: n_dim: 512 limit: 10 metas: py_modules: - annlite.executor workspace: './workspace' ```
```{code-block} python --- emphasize-lines: 4 --- from clip_client import Client c = Client( 'grpcs://api.clip.jina.ai:2096', credential={'Authorization': ''} ) r = c.encode( [ 'First do it', 'then do it right', 'then do it better', 'https://picsum.photos/200', ] ) ```
```{code-block} python --- emphasize-lines: 4 --- from clip_client import Client c = Client( 'https://api.clip.jina.ai:8443', credential={'Authorization': ''} ) r = c.encode( [ 'First do it', 'then do it right', 'then do it better', 'https://picsum.photos/200', ] ) ```
Trending Discussions on jina
Trending Discussions on jina
QUESTION
i have a table like this:
id person 20 adams 20 george 40 jina 46 rico 80 naya 90 john 90 peter 90 richardi want to find a way to select a new_id starting from 1 and increazing +1 every time id is different. for example i want a select with a result like this:
new_id id person 1 20 adams 1 20 george 2 40 jina 3 46 rico 4 80 naya 5 90 john 5 90 peter 5 90 richardis there any function in postgres doing something like that?
ANSWER
Answered 2022-Feb-16 at 11:13use dense_rank()
select dense_rank()over(order by id) as newid,id,persion
from table_name
QUESTION
In the dropdownlist field when option Jiná společnost:
is selected I need to show that the JinaSpolecnostTextBox
textbox
Can you help me?
$('[PrimaGroupList]').change(function() {
var SelectedValue = $('[PrimaGroupList]').val();
if (SelectedValue == "Jiná společnost:")
$("#JinaSpolecnost").show();
else
$("#JinaSpolecnost").hide();
})
Vyberte z možností *
FTV Prima, spol. s r. o.
MEDIA CLUB, s.r.o.
PRIMA GROUP MANAŽERSKÁ, a.s.
PRIMA DOMA MEDIA, s.r.o.
CAR PR MEDIA, s.r.o.
Prima produkce, s.r.o.
PLAYzone s.r.o.
PLAYPRESS s.r.o.
RADIO UNITED BROADCASTING s.r.o.
Jiná společnost (uveďte)
Název jiné společnosti *
ANSWER
Answered 2022-Jan-27 at 10:00The issue in your code is because $('[PrimaGroupList]')
isn't a valid selector. You need to use the 'attribute selector' to retrieve the element by its name
. The code should look like this:
let $textbox = $("#JinaSpolecnost");
$('select[name="[PrimaGroupList]"]').change(function() {
var selectedValue = $(this).val();
if (selectedValue == "Jiná společnost:")
$textbox.show();
else
$textbox.hide();
})
Vyberte z možností *
FTV Prima, spol. s r. o.
MEDIA CLUB, s.r.o.
PRIMA GROUP MANAŽERSKÁ, a.s.
PRIMA DOMA MEDIA, s.r.o.
CAR PR MEDIA, s.r.o.
Prima produkce, s.r.o.
PLAYzone s.r.o.
PLAYPRESS s.r.o.
RADIO UNITED BROADCASTING s.r.o.
Jiná společnost (uveďte)
Název jiné společnosti *
QUESTION
Context:
I have a Topic
enum:
public enum Topic {
RELATIONSHIP, DATING, EDUCATION, FITNESS, NEWS, RENT, EVENTS, GIVEAWAY, SALE
}
and a class Member with a topics list as field. A member has at least one and up to 9 topics, to which he/she has subscribed.
@AllArgsConstructor
@Getter
@ToString
static class Member {
String id;
List topics;
String email;
}
Once a week I get a list of Messages. Each messages belongs to exactly one Topic type. The list of Messages doesn't contain Messages, which have the same topic (no duplicate topics and never empty, 1 to 9 entries)
@AllArgsConstructor
@Getter
@ToString
static class Message {
String id;
Topic topic;
String content;
}
Question:
Given a list of messages and a list of members create a map Map>
to be used to send each member a notification. Each member should only receive notifications for topics, to which he/she has subscribed.
My approach:
- Create a
Map
from messages list (done as you can see in the example below) - Create a
Map>
from members list. (I am stuck here, don't know how to extract single Topics from members topic list to create my desired map) - after I get the above two maps create a final map
>
mapping the values of first map to corresponding values of second map. Should be easy.
Example setup:
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
public class Example {
public static void main(String[] args) {
List messages = List.of(new Message("KW41",Topic.EDUCATION,"Some educational content published"),
new Message("KW41",Topic.FITNESS,"Some fitness content published"),
new Message("KW41",Topic.DATING,"Some dating content published"),
new Message("KW41",Topic.RENT,"Some rent content published"));
List memberList = List.of(new Member("1", List.of(Topic.SALE, Topic.RENT), "john@gmail.com"),
new Member("2", List.of(Topic.DATING, Topic.NEWS), "jess@gmail.com"),
new Member("3", List.of(Topic.EDUCATION), "jane@gmail.com"),
new Member("4", List.of(Topic.FITNESS, Topic.RENT, Topic.EDUCATION), "jojo@gmail.com"),
new Member("5", List.of(Topic.RELATIONSHIP), "jina@gmail.com"),
new Member("6", List.of(Topic.SALE, Topic.NEWS), "jimi@gmail.com"),
new Member("7", List.of(Topic.NEWS, Topic.EVENTS), "jd@gmail.com"));
Map messageMap = messages.stream().collect(Collectors.toMap(Message::getTopic, Function.identity()));
messageMap.entrySet().forEach(System.out::println);
}
@AllArgsConstructor
@Getter
@ToString
static class Member {
String id;
List topics;
String email;
}
@AllArgsConstructor
@Getter
@ToString
static class Message {
String id;
Topic topic;
String content;
}
enum Topic {
RELATIONSHIP, DATING, EDUCATION, FITNESS, NEWS, RENT, EVENTS, GIVEAWAY, SALE
}
}
How can i get from the members list a Map>
grouped by topics. (I cant't easily do stream.collect(Collectors.groupingBy(Member::getTopics))
since it is a list. I need to extract them somehow before). Desired map should contain (adding only members ids for readability)
Topic.RELATIONSHIP=[5]
Topic.DATING=[2]
Topic.EDUCATION=[3, 4]
Topic.FITNESS=[4]
Topic.NEWS=[2, 6, 7]
Topic.RENT=[1, 4]
Topic.EVENTS=[7]
Topic.SALE=[1, 6]
ANSWER
Answered 2021-Oct-12 at 17:05Flattening into tuples could help.
For example with:
@Value
class Tuple {
L left;
R right;
}
You could have:
Stream stream = ...;
Map> result = stream
.flatMap(member -> member.getTopics().stream().map(topic -> new Tuple<>(topic, member)))
.collect(groupingBy(Tuple::getLeft, mapping(Tuple::getRight, toList())));
QUESTION
I am getting one list of objects from the database and iterate through that list inside html page with thymeleaf engine using th:switch and th:each. Now I want to change one property from each object from this list to another format, The problem is how do I use those formatted value inside another list in switch statement in thymeleaf with it's corresponding object from the first list.
Below shows how I loop inside every object to get the value of getKinachoitajika() which is a double number that appears as 5.0E7 in output, now I format it so as to get a display of normal number like 50,000,000 and put those value into an ArrayList of arrItajika and use them inside html file while looping through the objects of the first list.
@GetMapping("/joinMichangoQuery")
public String kandaAndParokia(Model model){
List listKandaAndParokia = kMichangoRepository.findAll();
ArrayList arrItajika = new ArrayList<>();
for(int i=0; i< listKandaAndParokia.size(); i++){
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(0);
arrItajika.add(nf.format(listKandaAndParokia.get(i).getKinachoitajika()));
}
model.addAttribute("listKandaAndParokia", listKandaAndParokia);
model.addAttribute("itajikaFromated", arrItajika);
return "michango_joined";
}
Now inside michango_joined.html I iterate through all the values of each object and display them on the table as below.
No Michango
ID
KandaID
Kinachohitajika
Kilichopatikana
Hali
Jina La Mchango toka Parokia Michango
[[${kMchango.mchangoParokia.status}]]
Now I want to use the value of the ArrayList arrItajika to be display with each corresponding objects within the switch, meaning I want to replace this "${kMchango.kinachoitajika}" with my arrItajika inside thymeleaf, How do I perform this interaction or is there another suggestion on how I can handle this.
Update: I have added the Repository file
public interface KmichangoRepository extends JpaRepository {
@Query(value = "SELECT * FROM michango_kanda INNER JOIN michango ON michango_kanda.mchango_code = michango.mchango_code",nativeQuery = true)
public List getKandaAndParokiaByMichangoCode();
}
ANSWER
Answered 2021-Mar-12 at 13:36If the indexes of both lists are equal, you can use th:each
with an index. See Thymeleaf - How to loop a list by index
...
...
Alternatively, create a new class that combines Kmichango
with an extra field that is the formatted value and have just 1 list in your model with elements of that new type of class.
Finally, you can also do the formatting in the template itself:
QUESTION
I try to generate csv file from json type data. These are my json test data.
{
"realtime_start":"2020-09-25",
"realtime_end":"2020-09-25",,
"units": "Percent",
"seriess": [
{
"name": "James",
"age": 29,
"house": "CA"
},
{
"name": "Jina",
"age": 39,
"house": "MA",
"notes": "Million tonne punch"
},
}
The problem is json array type "seriess
" does not contain "notes"
node in all every nodes. I made the below java codes to change this json data to csv file with header columns
JSONObject json = getJsonFileFromURL(...)
JSONArray docsArray = json.getJSONArray("seriess");
docsArray.put(json.get("realtime_start"));
docsArray.put(json.get("realtime_end"));
docsArray.put(json.get("units"));
JsonNode jsonTree = new ObjectMapper().readTree(docsArray.toString());
Builder csvSchemaBuilder = CsvSchema.builder();
for(JsonNode node : jsonTree) {
node.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);} );
}
CsvSchema csvSchema = csvSchemaBuilder.build().withHeader();
CsvMapper csvMapper = new CsvMapper();
csvMapper.writerFor(JsonNode.class).with(csvSchema).writeValue(new File("test.csv"), jsonTree);
But the incorrect results are shown like below,
realtime_start,realtime_end,units,names,age,house,realtime_start,realtime_end,units,names,age,house,notes, realtime_start,.....
The generated header columns does not contain distinct values. The header columns are added in duplicate. How can I generate the distinct header like below
realtime_start,realtime_end,units,names,age,house, notes
Any idea?
Update PartI try to extract data from the FRED (FEDERAL RESERVE BANK OF ST. LOUIS). FRED provide simple and convenient Python api like below,
from fredapi import Fred
import pandas as pd
fred = Fred(api_key='abcdefghijklmnopqrstuvwxyz0123456789')
data_unemploy = fred.search('Unemployment Rate in California')
data_unemploy.to_csv("test_unemploy.csv")
But the java apis are deprecated, so I have to develop simple Java api which convert json values to csv file. I found the below Java codes with googling
JSONObject json = getJsonFileFromURL("https://api.stlouisfed.org/fred/series/search?search_text=Unemployment+Rate+in+California&api_key=abcdefghijklmnopqrstuvwxyz0123456789&file_type=json");
JSONArray docsArray = json.getJSONArray("seriess");
docsArray.put(json.get("realtime_start"));
docsArray.put(json.get("realtime_end"));
JsonNode jsonTree = new ObjectMapper().readTree(docsArray.toString());
JsonNode firstObject = jsonTree.elements().next(); // I am struggling with this line
firstObject.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);} );
CsvSchema csvSchema = csvSchemaBuilder.build().withHeader();
CsvMapper csvMapper = new CsvMapper();
csvMapper.writerFor(JsonNode.class).with(csvSchema).writeValue(new File("test.csv"), jsonTree);
To extract columns from json data JsonNode firstObject = jsonTree.elements().next();
return the first json node. But this line does not return notes
column. because the first line does not contain the notes
key value.
So I change this code line to following lines
for(JsonNode node : jsonTree) {
node.fieldNames().forEachRemaining(fieldName -> {
csvSchemaBuilder.addColumn(fieldName);
} );
}
But these lines throws the results which I do not expect. The repeated duplicated columns like below
realtime_start,realtime_end,units,names,age,house,realtime_start,realtime_end,units,names,age,house,notes, realtime_start,.....
I am totally stuck with this part.
ANSWER
Answered 2020-Sep-26 at 07:47You can do it with a library Apache Commons IO
pom.xml
commons-io
commons-io
2.6
ConvertJsonToCSVTest.java
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.json.*;
public class ConvertJsonToCSVTest {
public static void main(String[] args) throws JSONException {
String jsonArrayString = "{\"fileName\": [{\"first name\": \"Adam\",\"last name\": \"Smith\",\"location\": \"London\"}]}";
JSONObject output;
try {
output = new JSONObject(jsonArrayString);
JSONArray docs = output.getJSONArray("fileName");
File file = new File("EmpDetails.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
System.out.println("Data has been Sucessfully Writeen to "+ file);
System.out.println(csv);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Data has been Sucessfully Writeen to EmpDetails.csv
last name,first name,location
Smith,Adam,London
QUESTION
In my desktop version, I have some code that allows you to hover over a button to reveal some info/text. How do I reset this in mobile to not do anything at all when tapped on.
.credit:hover .credit-text,
.credit-ba:hover .credit-text {
display: block;
}
Instead I wanted to write a JS rule on the the icon to make it clickable - so toggle hide and showing on clicking icon. The issue with the hover click on phone is that, the user has to click around the screen to close the open tab, instead of clicking the button/icon again.
.hideElement {
display: none;
}
Here is JS
const creditIcon = document.querySelector('.credit-icon');
const creditText = document.querySelector('.credit-text');
let creditOpen = false;
creditIcon.addEventListener('click', () => {
creditText.style.display = "block";
creditOpen = processMenu.classList.contains('hideElement')
})
HTML
(...)
Thank you
to my team of helpers
and the following
Collaborators
Handmade Staples Details produced by Mary Chan
Knitwear produced by Elaine Lip
Shoes Handcrafted by Doyeon Ji
Soundtrack composed by Zacharias Wolfe
Look Book
Photographed by Dean Hoy
Make Up by Ana Takahashi
Show
Hair by L’Oréal Professionnel
Make Up by MAC Cosmetics
Supported by ThreeUK
Models
Jina Yoo
Aaron Wong
Reign Charbit
Karen Reichelt
Harrison Chan
Jessica Chen
Kristianna Peel
Trinity Mcintosh
Special thanks to Lane Crawford
and the MAFCSM team
ANSWER
Answered 2020-Sep-18 at 10:20Try with this media query
@media not all and (pointer: coarse) {
.credit:hover .credit-text,
.credit-ba:hover .credit-text {
display: block;
}
}
const creditIcon = document.querySelector('.credit-icon');
const creditText = document.querySelector('.credit-text');
let creditOpen = false;
creditIcon.addEventListener('click', () => {
creditText.style.display = "block";
creditOpen = processMenu.classList.contains('hideElement')
})
@media not all and (pointer: coarse) {
.credit:hover .credit-text,
.credit-ba:hover .credit-text {
display: block;
}
}
.hideElement {
display: none;
}
(...)
Thank you
to my team of helpers
and the following
Collaborators
Handmade Staples Details produced by Mary Chan
Knitwear produced by Elaine Lip
Shoes Handcrafted by Doyeon Ji
Soundtrack composed by Zacharias Wolfe
Look Book
Photographed by Dean Hoy
Make Up by Ana Takahashi
Show
Hair by L’Oréal Professionnel
Make Up by MAC Cosmetics
Supported by ThreeUK
Models
Jina Yoo
Aaron Wong
Reign Charbit
Karen Reichelt
Harrison Chan
Jessica Chen
Kristianna Peel
Trinity Mcintosh
Special thanks to Lane Crawford
and the MAFCSM team
QUESTION
I am using MongoDB via mongoose.
What happens when you query an indexed field with a non-indexed field? See code below.
// For example
MyModel.find({ _id: '123', name: 'Jina'});
Does MongoDB do a collection scan or does the index help in making the query efficient? And is the query any different from just using the _id
field?
If MongoDB does a collection scan when you query a non-indexed field. Does querying multiple non-indexed fields speed up the query speed if a collection scan will be done all the same? Lets say if I query five non-indexed fields as opposed to two(both returning the same document(s)). Did both queries do the same collection scan?
ANSWER
Answered 2020-Jun-21 at 07:39To understand what is happening under the hood in mongo queries, you can use explain
. For example, consider the following query: db.getCollection('users').find({"name":"ana"})
which queries a non-indexed field. You can use explain on this query as below:
db.getCollection('users').find({"name":"ana"}).explain("executionStats")
Part of the result is:
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "anonymous-chat.users",
"indexFilterSet" : false,
"parsedQuery" : {
"name" : {
"$eq" : "ana"
}
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"name" : {
"$eq" : "ana"
}
},
"direction" : "forward"
},
"rejectedPlans" : []
},
As you can see, here we had a COLLSCAN
which is a collection scan. Now we just query _id and see the result:
db.getCollection('users').find({"_id":ObjectId("5ee9b6c125b9a9a426d9965f")}).explain("executionStats")
Here is the result:
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "anonymous-chat.users",
"indexFilterSet" : false,
"parsedQuery" : {
"_id" : {
"$eq" : ObjectId("5ee9b6c125b9a9a426d9965f")
}
},
"winningPlan" : {
"stage" : "IDHACK"
},
"rejectedPlans" : []
},
As we can see, we have IDHACK
when querying just _id.
Now we combine _id and name:
db.getCollection('users').find({"_id":ObjectId("5ee9b6c125b9a9a426d9965f"), "name":"ana"}).explain("executionStats")
This is the result:
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "anonymous-chat.users",
"indexFilterSet" : false,
"parsedQuery" : {
"$and" : [
{
"_id" : {
"$eq" : ObjectId("5ee9b6c125b9a9a426d9965f")
}
},
{
"name" : {
"$eq" : "ana"
}
}
]
},
"winningPlan" : {
"stage" : "FETCH",
"filter" : {
"name" : {
"$eq" : "ana"
}
},
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"_id" : 1
},
"indexName" : "_id_",
"isMultiKey" : false,
"multiKeyPaths" : {
"_id" : []
},
"isUnique" : true,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"_id" : [
"[ObjectId('5ee9b6c125b9a9a426d9965f'), ObjectId('5ee9b6c125b9a9a426d9965f')]"
]
}
}
},
"rejectedPlans" : []
},
As we can see, The index helped with the query performance as we have two stages, an IXSCAN
(Index Scan) and a FETCH
stage which filters the documents of the last stage.
Now let's query multiple non-indexed fields to find out about your second question:
db.getCollection('users').find({"name":"ana", "appId":1}).explain("executionStats")
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "anonymous-chat.users",
"indexFilterSet" : false,
"parsedQuery" : {
"$and" : [
{
"appId" : {
"$eq" : 1.0
}
},
{
"name" : {
"$eq" : "ana"
}
}
]
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"$and" : [
{
"appId" : {
"$eq" : 1.0
}
},
{
"name" : {
"$eq" : "ana"
}
}
]
},
"direction" : "forward"
},
"rejectedPlans" : []
},
There is only one collection scan for multiple fields as we can see above.
QUESTION
I have two dropdowns in my .html file of Django app namely:
op1
opt1
A dictionary is rendered from the Django views.py.I want the keys to be displayed as options in the first dropdown and whenever a key is selected,the corresponding values need to be displayed in the second dropdown.I tried some js and jina Template but no luck.How can I implement it? I tried the following js:
function myFunction() {
var dict=[];
dict.push("{{Names}}");
alert(Object.keys(dict));
}
My returned dictionary is of the form:
Names={1991:["cat & dog","Mat-bat","task force"],1992:["average life span!","text-user"]}
output:0 Django views.py:
def home(requests):
return render(requests,'home/index.html',{"Names":getNames()})
ANSWER
Answered 2020-Jun-19 at 14:35You can use Django's template rendering to populate the first dropdown, something like:
{% for key, values in yourdict %}
{{ key }}
{% endfor %}
Make sure to pass your dictionary variable to the template and replace "yourdict" with whatever your dictionary variable is called.
You then need to use javascript / jquery to populate the second dropdown. Add an onchange function to your first dropdown:
Then in JS you can define that function:
function populateSecond() {
var select1 = document.getElementById("exampleFormControlSelect1");
var select2 = document.getElementById("exampleFormControlSelect2");
var selectedValue = select1.options[select1.selectedIndex].value;
selectedValue.forEach(function(element){
select2.appendChild(element);
}
}
This requires that your stored values in the first dropdown are recognized as an array. Im not sure if they will be off hand, but if not you may have to convert the value of selectedValue from a string to an array using the split() method
QUESTION
I am in my homepage template where I have only search box like google main search page looks like, Now I want to search variables from another template and display it but nothing happen. Below is my code
Homepage template
Home page view
def IndexView(request):
title="Homepage"
return render(request, "loststuffapp/home.html", {"title":title})
Miscellaneous template
Jina la nyaraka: {{Doc.docs_name}}
Aina ya nyaraka: {{Doc.item_type}}
{% if Doc.image %}
{% endif %}
{{Doc.date}}
Miscellaneous view
def Miscellaneous(request):
query = request.GET.get('q', '')
qsets=(Q(docs_name__icontains=query)|Q(item_type__icontains=query))
return render(request, "loststuffapp/Miscellaneous.html", context={"documents":Documents.objects.filter(qsets)})
ANSWER
Answered 2020-Jan-18 at 13:30If I understand you correctly you want to pass the q parameter from the form on your home page to the Miscellaneous view. Currently your code just calls your IndexView in submitting the form and returns to it.
I guess you are expecting that the form to submit to the Miscellaneous view by adding the url to onclick
of your button. I do not think that works like that as onclick
expects some javascript function. Your form submits to the url you put into the action attribute of your form, and this is your homepage.
So the simplest approach would be to change the action attribute of your form to point to your Miscellaneous view:
Remark: I am not sure what you expect from the value attribute or your form
What you can do also is to return to your IndexView
on submit of the form and redirect from there to the MiscellaneaousView
, passing the query as an argument. However, this does not look necessary from what I read from your post.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install jina
We promise you can build a scalable ResNet-powered image search service in 20 minutes or less, from scratch to Kubernetes. If not, you can forget about Jina.
Import what we need.
Import what we need. from docarray import Document, DocumentArray from jina import Executor, Flow, requests
Copy-paste the preprocessing step and wrap it via Executor: class PreprocImg(Executor): @requests async def foo(self, docs: DocumentArray, **kwargs): for d in docs: ( d.load_uri_to_image_tensor(200, 200) # load .set_image_tensor_normalization() # normalize color .set_image_tensor_channel_axis( -1, 0 ) # switch color axis for the PyTorch model later )
Copy-paste the embedding step and wrap it via Executor: class EmbedImg(Executor): def __init__(self, **kwargs): super().__init__(**kwargs) import torchvision self.model = torchvision.models.resnet50(pretrained=True) @requests async def foo(self, docs: DocumentArray, **kwargs): docs.embed(self.model)
Wrap the matching step into an Executor: class MatchImg(Executor): _da = DocumentArray() @requests(on='/index') async def index(self, docs: DocumentArray, **kwargs): self._da.extend(docs) docs.clear() # clear content to save bandwidth @requests(on='/search') async def foo(self, docs: DocumentArray, **kwargs): docs.match(self._da, limit=9) del docs[...][:, ('embedding', 'tensor')] # save bandwidth as it is not needed
Connect all Executors in a Flow, scale embedding to 3: f = ( Flow(port_expose=12345) .add(uses=PreprocImg) .add(uses=EmbedImg, replicas=3) .add(uses=MatchImg) ) Plot it via f.plot('flow.svg') and you get:
Download the image dataset.
Index image data: with f: f.post( '/index', index_data, show_progress=True, request_size=8, ) f.block()
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page